#!/bin/sh

##########################################################################
#   Script description:
#       Common admin tasks
#       
#   History:
#   Date        Name        Modification
#   2016-01-01  J Bacon     Begin
##########################################################################

usage()
{
    printf "Usage: $0\n"
    exit 1
}


##########################################################################
#   Function description:
#       Pause until user presses return
##########################################################################

pause()
{
    local junk
    
    printf "Press return to continue..."
    read junk
}


##########################################################################
#   Main
##########################################################################

if [ $# != 0 ]; then
    usage
fi

# Prevent user from running a Trojan as root in the case their account
# was compromised
absolute="$(which $0)"
# Don't count on -e being set at this point
if ! auto-file-secure "$absolute"; then
    exit 1
fi

if ! auto-root-check $0; then
    printf "Root "
    # exec quotes '$absolute --flag', causing usage error
    # Assigning to cmd works around the problem
    cmd="$absolute $@"
    exec su -m root -c "$cmd"
fi

case $(auto-ostype) in
FreeBSD|NetBSD)
    poweroff=-p
    suspend_cmd="acpiconf -s 3"
    ;;

RHEL)
    poweroff=-h
    suspend_cmd="systemctl suspend"
    ;;

*)
    printf "$0: poweroff flag undefined for $(auto-ostype).\n"
    pause
    ;;

esac

while true
do
    clear
    auto-admin-banner
    cat << EOM

1.. Power off
2.. Restart
3.. Sleep
Q.. Quit

EOM

    printf "Selection? "
    read resp
    if [ 0"$resp" = 0q ]; then
	break
    fi
    printf '\nThe following users are currently logged in:\n\n'
    w
    printf '\nAre you sure you want to proceed? y/[n] '
    read proceed
    if [ 0$proceed = 0y ]; then
	case 0$resp in
	01)
	    printf "Minutes to shutdown? [2] "
	    read minutes
	    if [ 0$minutes = 0 ]; then
		minutes=2
	    fi
	    shutdown $poweroff +$minutes
	    ;;
	
	02)
	    printf "Minutes to restart? [2] "
	    read minutes
	    if [ 0$minutes = 0 ]; then
		minutes=2
	    fi
	    shutdown -r +$minutes
	    ;;
	
	03)
	    printf "Minutes before sleep mode? [2] "
	    read minutes
	    if [ 0$minutes = 0 ]; then
		minutes=2
	    fi
	    c=0;
	    while [ $c -lt $minutes ]; do
		sleep 1
	    done
	    $suspend_cmd
	    ;;
	esac
    fi
done
