#!/bin/bash

#
# shutdown_os9
#
# Jason Healy
#
# Sends a remote shutdown command to one or more machines running Mac OS 9.
# A helper AppleScript must already be installed on the target machine(s).
#
# For more information, see the documentation for this project.
#


# Default username to use when connecting to remote machines
DEFAULT_USERNAME="shutdown"

# Default password to use when connecting to remote machines
DEFAULT_PASSWORD="<supersecret>"

# Script name to call on the remote machine ("CommTest" or "ForcedShutDown")
# Script must be located in the "RemoteShutdown" folder on the system drive
REMOTE_SCRIPT="CommTest"


# function to shut down a single machine
# Requires a single argument in the form of 'user:pass@host' or just 'host'
#
# This function can be backgrounded to allow for parallel processing of
# multiple machines (usually a good idea, since the script has several
# seconds of delay per host).
#
function shutdown_machine {

    local hostspec=$1
    # make a version without the password
    local nopw=${hostspec##*@}

    logger -p daemon.alert -t shutdown_os9 "Shutting down host ${nopw}"

    output=$(osascript -l AppleScript -e \
            "tell Application \"Finder\" \
            of machine \"eppc://${hostspec}\" \
            to open file \"${REMOTE_SCRIPT}\" \
            of folder \"RemoteShutdown\" of startup disk" \
            2>&1)

    if [ "${output}" != "${REMOTE_SCRIPT}" ]; then
	logger -p daemon.alert -t shutdown_os9 "Warning: ${nopw} returned ${output}"
    fi

}


# Main program
#
# Loop through all machine specifications and shut down each in turn.
#

for machine in $@; do

    if (echo "${machine}" | grep -q '[^:@.%a-zA-Z0-9-]'); then

	logger -p daemon.warn -t shutdown_os9 "Host '${machine}' has illegal specification"

    elif (echo "${machine}" | grep -q '[:@]'); then

	shutdown_machine ${machine} &

    else

	logger -p daemon.debug -t shutdown_os9 "Using default username and password for ${machine}"

	shutdown_machine "${DEFAULT_USERNAME}:${DEFAULT_PASSWORD}@${machine}" &

    fi

done
