925becc55a95ffc3ddc2f3f1816643ef3474e50c
[automated-distro-installer] / chboot
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 # Set grub to boot into a different distro, and reboot unless -r
19 # $0 [DISTRO_NAME]
20 # with no argument, print available distros
21
22 # DISTRO_NAME is based on the partition names in /boot. eg boot_debianjessie
23
24 set -eE -o pipefail
25 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
26
27 [[ $EUID == 0 ]] || exec sudo "$BASH_SOURCE" "$@"
28
29
30 ###### begin command line parsing #####
31 reboot=true
32 while [[ $1 == -* ]]; do
33 case $1 in
34 -d) set -x; shift ;;
35 -r) reboot=false; shift ;;
36 --) break ;;
37 esac
38 done
39
40
41 distro=$1
42
43 if [[ ! $distro ]]; then
44 echo "available distros:"
45 btrfs subvolume list /boot | sed -rn 's/^.*boot_(.*)/\1/p'
46 exit 0
47 fi
48
49 ###### end command line parsing #####
50
51
52 #### begin initial error checking #####
53
54 if ! btrfs subvolume list /boot | grep "_$distro$" &>/dev/null; then
55 echo "$0: error: _$distro$ not found in btrfs subvolume list /boot:"
56 btrfs subvolume list /boot
57 exit 1
58 fi
59
60 #### end initial error checking #####
61
62 e() { echo "$@"; "$@"; }
63
64 boot_dev=$(mount | sed -rn "s#^(\S+) on /boot .*#\1#p")
65
66 mount_point=$(mktemp -d)
67
68 e mount -o subvol=boot_$distro $boot_dev $mount_point
69
70 boot_disk=${boot_dev%%[0-9]*}
71
72 # arch doesn't have $mount_point/grub/device.map, accoring to the grub manual,
73 # it just generates one if the file doesn't exist.
74 # https://www.gnu.org/software/grub/manual/html_node/Device-map.html
75 e grub-bios-setup -d $mount_point/grub/i386-pc -s -m $mount_point/grub/device.map $boot_disk
76
77 e umount $mount_point
78 e rmdir $mount_point
79
80 if $reboot; then
81 touch /tmp/keyscript-off
82 reboot now
83 fi