#!/bin/bash
#
# Copyright (c) 2006-2013 University of Utah and the Flux Group.
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
. /etc/emulab/paths.sh

#
# tbprepare       Run "prepare" on the way down.
#
### BEGIN INIT INFO
# Provides: tbprepare
# Required-Start:
# Required-Stop: $network
# Should-Start:
# Should-Stop:
# Default-Start:
# Default-Stop: 1 6
# Short-Description: Clean up node using Emulab's prepare script.
# Description:       Clean up node using Emulab's prepare script.
### END INIT INFO
#
# The fields below are left around for legacy tools (will remove later).
#
# chkconfig: 16 89 89
# description:  Clean up node using Emulab's prepare script.
#

# Source networking configuration.
if [ -f /etc/sysconfig/network ]; then
    . /etc/sysconfig/network
elif [ -f /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
fi

RETVAL=0

# Oh, give me a break! Linux rc greps for keywords "daemon |action " to
# determine if stdout/stderr should be redirected! So, put this stupid
# line here so that output goes to the console!
#
# daemon action 

# See how we were called.
case "$1" in
  start)
	# We do not do anything; this is strictly for reboot time.
	# Note: /var/lock/subsys/tbprepare will be created later, as needed.
	;;
  stop)
        #
        # Note the Ubuntu does not use the /var/lock/subsys files
        # so we will get here on every shutdown, not just when the
        # subsys file exists.
        #
        if [ -f /var/lock/subsys/tbprepare ]; then
  	    rm -f /var/lock/subsys/tbprepare
	    echo "Running Testbed prepare script ..."
	    $BINDIR/prepare 2>&1 | tee /prepare.log
	    $BINDIR/logboot /prepare.log
	    rm -f /prepare.log
	    echo "Informing the testbed we're rebooting ..."
	    $BINDIR/tmcc state SHUTDOWN
	    RETVAL=$?
	fi
	;;
  status)
	echo "Peachy"
	;;
  restart)
	echo "Done"
	;;
  reload)
	echo "Done"
	;;
  *)
	echo "Usage: testbed {start|stop|restart|reload|status}"
	exit 1
esac

exit $RETVAL
