#!/bin/sh
#
# halt - halt the system

# Flush all buffered data to the only remaining disk: the Root File System (JFFS2).
# We are assuming that all flash writes are physically complete after the sync.
# The 1 second sleep is insurance.
echo "`date` executing sync and sleeping for 1 second"
sync
sleep 1

source /usr/local/lib/http_helper

# Do the testcode the old way with separate HTTP POSTS to ARM and PWM
testcode_arm_pwm_separate() 
{
	# Post to PWM first...we have 5 seconds to get the ARM post to succeed afterward
        # (if we do ARM first, we only have 2 seconds before we know we will cause problems)
	echo `date +"%Y-%m-%d %H:%M:%S.%6N"` " Asking PWM to Test Code..." > /dev/console		
	http_post_retry "http://1.0.0.2/pwm/testcode" -1
	if [ $? -eq 0 ]; then
		echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Asking ARM to Test Code..." > /dev/console
		http_post_retry "http://1.0.0.2/firmware/testcode" -1 > /dev/console
	fi
}

# Kill Heartbeat, if it is running
/usr/bin/pkill -9 hb.ppc

if [ -f /tmp/testcode ]; then
	echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Power off will do a testcode of ARM/DSP/PWM" > /dev/console
	rm /tmp/testcode
	http_post_retry "http://1.0.0.2/status/testcodeAll" -1
        # Handle old Taurus API (before Taurus Version 2.04.06)
	if [ $? -ne 0 ]; then
		testcode_arm_pwm_separate
	fi
	exit 0
fi

if [ -f /tmp/reboot ]; then
	echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Power off will do a complete reboot of ARM/DSP/PWM" > /dev/console
	rm /tmp/reboot
	http_post_retry "http://1.0.0.2/pwm/reboot" -1
	exit 0
fi

# Keep asking the ARM to turn off the PPC
# Loop just in case the ARM is busy.  Easier than checking response code
while [ true ]; do
  echo `date +"%Y-%m-%d %H:%M:%S.%6N"` "Asking ARM to power off PowerPC..." > /dev/console
  http_post "http://1.0.0.2/status/powerOff"
  sleep 2
done

# end of /etc/init.d/halt

