use disk/by-id if possibe, other small fixes
[automated-distro-installer] / chboot
1 #!/bin/bash -x
2
3 # Set grub to boot into a different distro, and reboot unless -r
4 # $0 [DISTRO_NAME]
5 # with no argument, print available distros
6
7 # DISTRO_NAME is based on the partition names in /boot. eg boot_debianjessie
8
9 set -eE -o pipefail
10 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?"' ERR
11
12 [[ $EUID == 0 ]] || exec sudo "$BASH_SOURCE" "$@"
13
14 reboot=true
15 while [[ $1 == -* ]]; do
16 case $1 in
17 -r) reboot=false; shift ;;
18 --) break ;;
19 esac
20 done
21
22
23 distro=$1
24
25 ###### end command line parsing #####
26
27 if [[ ! $distro ]]; then
28 echo "available distros:"
29 btrfs subvolume list /boot | sed -rn 's/^.*boot_(.*)/\1/p'
30 exit 0
31 fi
32
33 if ! btrfs subvolume list /boot | grep "_$distro$" &>/dev/null; then
34 echo "$0: error: _$distro$ not found in btrfs subvolume list /boot:"
35 btrfs subvolume list /boot
36 exit 1
37 fi
38
39 e() { echo "$@"; "$@"; }
40
41 boot_dev=$(mount | sed -rn "s#^(\S+) on /boot .*#\1#p")
42
43 mount_point=$(mktemp -d)
44
45 e mount -o subvol=boot_$distro $boot_dev $mount_point
46
47 boot_disk=${boot_dev%%[0-9]*}
48
49 # arch doesn't have $mount_point/grub/device.map, accoring to the grub manual,
50 # it just generates one if the file doesn't exist.
51 # https://www.gnu.org/software/grub/manual/html_node/Device-map.html
52 e grub-bios-setup -d $mount_point/grub/i386-pc -s -m $mount_point/grub/device.map $boot_disk
53
54 e umount $mount_point
55 e rmdir $mount_point
56
57 if $reboot; then
58 reboot now
59 fi