#!/bin/sh

. /etc/emulab/paths.sh

#
# XEN vms will just restart, so halt to really stop it.
# Luckily, OpenVZ VMs respect halt as well, so we can always halt
# inside of VMs.
#
dohalt=0
if [ -e "$BOOTDIR/vmname" ]; then
    dohalt=1
fi

reboot=1
if [ $# -eq 1 ]; then
    if [ "$1" = "-noreboot" ]; then
	reboot=0
    fi
fi

#
# Arrange for "prepare" to be run on the way down.
#
touch /var/lock/subsys/tbprepare

#
# If this Linux is using systemd as its init, make sure to "start" the tbprepare
# service.  systemd will not honor the K89tbprepare rc*.d symlinks *unless the
# tbprepare service has been started* -- and of course it doesn't "start" via
# an S89tbprepare link.  So we make sure systemd thinks it got started, and 
# then the K89tbprepare links will be run appropriately...
#
if [ -x /bin/systemd -o -x /lib/systemd/systemd ]; then
    echo "Emulab scheduling tbprepare to run via systemd."
    systemctl start tbprepare.service
fi

if [ $reboot -eq 1 ]; then
    if [ $dohalt -eq 1 ]; then
	# This little bit of sillyness is to ensure that this
	# script exits with zero status before the node halts.
        (sleep 1; /sbin/halt) >/dev/null 2>&1 </dev/null &
    else
        (sleep 1; /sbin/reboot) >/dev/null 2>&1 </dev/null &
    fi
fi
exit 0
