#!/bin/bash - 
#===============================================================================
#
#          FILE:  halt-host2.sh
# 
#         USAGE:  ./halt-host2.sh 
# 
#   DESCRIPTION:  Remotely halt boxes using ssh
# 
#       OPTIONS:  ---
#  REQUIREMENTS:  ---
#          BUGS:  ---
#         NOTES:  ---
#        AUTHOR: Roger Zauner (rdz), rogerx@sdf.org
#       COMPANY: N/A
#       CREATED: 03/26/2010 03:50:20 AM AKDT
#      REVISION:  ---
#===============================================================================

set -o nounset                              # Treat unset variables as an error
#set -o xtrace                               # Enable trace debugging

# First we should call on bash to exit safely using "kill -s SIGHUP $pid", use pidof to get a numerated
# listing of bash processes.

check_location()
{
    if [ ${HOSTNAME} != localhost2.local ] && [ $(ping -qc1 localhost2.local | grep errors| wc -l) -eq 0 ]; then
        PREFIX="ssh localhost2"
    else
        exit 0
    fi
}

exit_bash()
{
    #pidof_list=`pidof bash`

    #for i in pidof_list; do
    #    ${PREFIX} kill -s SIGHUP $i
    #done

    ${PREFIX} sudo chvt 1
    
    ${PREFIX} sudo halt -p &
    
    ${PREFIX} kill -s SIGHUP `${PREFIX} pidof bash`
}

safe_exit()
{
    ${PREFIX} killall elinks > /dev/null 2>&1
    ${PREFIX} killall mutt > /dev/null 2>&1
    ${PREFIX} killall calcurse > /dev/null 2>&1
    exit_bash
}

check_location

safe_exit

#Moved further up because halt will not execute w/o a bash environment!
#${PREFIX} sudo chvt 1
#${PREFIX} sudo halt -p &

#if [ $HOSTNAME != localhost2.local ] && [ $(ping -qc1 localhost2.local | grep errors| wc -l) -eq 0 ]; then
#    ssh localhost2 "sudo halt -p &" &
#elif [ $HOSTNAME = localhost2.local ]; then
#    sudo halt -p &
#fi

