scripts/kexec/kexec-reboot.sh
2023-04-15 10:05:08 -05:00

115 lines
2.1 KiB
Bash
Executable file

#!/bin/sh
set -e
[ -n "$BASH" ] && set -o pipefail
set -u
# defaults
wait=10
detach_wait=3
usage() {
cat << EOF
Usage: kreboot [option ...] [kernel|boot-index]
Options are:
--wait, -w N wait N seconds before reboot (default $wait)
--nowait don't wait, reboot immediately
--detach Schedule reboot and return. Suitable to remote reboot.
--help, -h show this help message
--kargs, k additional kernel arguments
Example:
$0 0 Boot kernel with index 0
EOF
exit $1
}
uerr() {
echo "ERROR: $*" 2>&1
echo
usage 1
}
# Check that all programs we need are available, exit if not
# (relying on 'set -e' and hash returning non-zero for errors)
hash grubby kexec systemctl
# Process options and arguments
target=''
kargs=''
while test $# -gt 0; do
case $1 in
-w|--wait)
if [ "$#" -lt 2 ]; then
uerr "Option $1 requires an argument"
fi
wait=$2
if ! printf "%f" $wait > /dev/null 2>&1; then
uerr "Option $1 argument not a number"
fi
shift
;;
--nowait)
wait=0
;;
--detach)
detach=yes
;;
--detach_wait)
if [ "$#" -lt 2 ]; then
uerr "Option $1 requires an argument"
fi
detach_wait=$2
if ! printf "%f" $detach_wait > /dev/null 2>&1; then
uerr "Option $1 argument not a number"
fi
shift
;;
-h|--help)
usage 0
;;
-k|--kargs)
kargs=$2
shift
;;
-*)
uerr "Unrecognized option: $1"
;;
*)
if [ -n "$target" ]; then
uerr "Extra arguments: $*"
fi
target=$1
;;
esac
shift
done
if [ -z "$target" ]; then
if ! target=$(grubby --default-kernel); then
# grubby prints error to stdout
echo "grubby: $target" 1>&2
exit 1
fi
fi
if ! info=$(grubby --info=$target); then
# grubby prints error to stdout
echo "grubby: $info" 1>&2
exit 1
fi
eval $(echo "$info" | sed "s|^\(\S*\)=\([^'\"].*\)$|\1='\2'|")
echo Booting $title...
if [ "$wait" -ne 0 ]; then
echo Press Ctrl-C within $wait seconds to cancel
sleep $wait
fi
kexec -l "$kernel" --initrd="$initrd" --command-line="root=$root $args $kargs"
if [ -z "detach" ]; then
systemctl kexec
else
setsid bash -c "sleep $detach_wait; systemctl kexec" &>/dev/null < /dev/null &
fi
`