#!/bin/sh -efu

# Copyright (C) 2010  Andrew V. Stepanov <stanv@altlinux.org>

#     ALTLinux shutdown, reboot, etc.. tools comming from SysVinit package.
#     Using SysVinit package, and all its infrastructure is tedious.
#     This script is attended to replace standard /sbin/reboot.
#     Nevertheless, this script requires kernel with enabled "magic SysRq key".
#     Using this script is unsafe! It uses bruteforce, and don't correctly shutdown devices.

PROG="${PROG:-${0##*/}}"

msg() {
    local msg="$@"
    if [ -z "$(echo $msg | sed -e 's/[[:space:]]//g')" ]; then
        return
    fi
    echo "$PROG: $msg"
}

if ! [ -e "/proc/sys/kernel/sysrq" -a -e "/proc/sysrq-trigger" ]; then
    msg "Kernel without SysRq support. Can't further execution."
    exit -1
fi

msg "Activate the magic SysRq option"
echo 1 > /proc/sys/kernel/sysrq

msg "Attempt to sync all mounted filesystems"
echo s > /proc/sysrq-trigger

msg "Attempt to remount all mounted filesystems read-only"
echo u > /proc/sysrq-trigger

msg "Reboot the machine"
sleep 2
echo b > /proc/sysrq-trigger
