#!/bin/sh
#
# VMTux.net
#
# /etc/vmt/vmt-stop
#
PATH=/bin:/sbin

if [ "$(id -u)" -ne 0 ]; then echo "This command can only be used by root" >&2 ; exit 1; fi

umask 022

. /etc/vmt/vmt-colors
. /etc/vmt/vmt-conf

clear 

if [ -x /opt/shutdown.sh ]; then
  echo -n "${BBlue}Runnning /opt/shutdown.sh ${Reset}"
  /opt/shutdown.sh >/dev/null 2>&1
  echo "${BGreen}done.${Reset}"
fi

echo -n "${BBlue}Syncing all filesystems "
sync
# wait for any outstanding sync requests
sync
# now we are synced (this is the only reason to sync twice)

echo "${BGreen}done.${Reset}"

echo -n "${BBlue}Stopping hotplug system "
/etc/init.d/mdev.init stop
echo "${BGreen}done.${Reset}"

echo -n "${BBlue}Disabling swap space "
swapoff -a 2>/dev/null
echo "${BGreen}done.${Reset}"

# prevent killing klogd else kernelmessages are redirected to console
OMMIT=""
if [ -f /var/run/klogd.pid ]; then
  OMMIT="-o $(cat /var/run/klogd.pid)"
fi

echo "${BRed}Killing all running processes.${Reset}"
killall5 $OMMIT && sleep 2
echo "${BRed}Terminating all running processes.${Reset}"
killall5 -9 $OMMIT 

# umount all packages
echo -n "${BBlue}Unmounting all packages "
find ${VMT_LOOP} -maxdepth 1 -type d -exec umount -d {} \; 2>/dev/null;
echo "${BGreen}done.${Reset}"

# Umount filesystems.
echo -n "${BBlue}Unmounting all filesystems "
umount -afr >/dev/null 2>&1
echo "${BGreen}done.${Reset}"

echo "${BPurple}Shutdown in progress.${Reset}"
echo

exit 0
