#!/bin/sh
#
# $Id: usb-watchdog-helper 7228 2010-11-19 18:42:53Z NiLuJe $
#

# Pull some helper functions for logging
_FUNCTIONS=/etc/rc.d/functions
[ -f ${_FUNCTIONS} ] && . ${_FUNCTIONS}

LINKSS_BASEDIR="/mnt/us/linkss"
WATCHDOG_PID="${LINKSS_BASEDIR}/run/usb-watchdog.pid"
USBWD_REBOOT_FILE="${LINKSS_BASEDIR}/reboot"
# Lock file. It needs to be outside of the userstore, because vfat doesn't handle hardlinks, and we need hardlinks for atomic locking.
USBWD_LOCK_DIR="/var/local/run"
USBWD_LOCK_FILE="${USBWD_LOCK_DIR}/usbwd.lock"
# shlock binary
USBWD_LOCK_BIN="${LINKSS_BASEDIR}/bin/shlock"
# Make sure shlock is exec'able
[ -x ${USBWD_LOCK_BIN} ] || chmod +x ${USBWD_LOCK_BIN}
# Make sure our lockfile has somewhere to live
[ -d ${USBWD_LOCK_DIR} ] || mkdir -p ${USBWD_LOCK_DIR}

# Add the PID of the dbus-monitor(s) to the list of running daemons to kill
echo "$( pidof dbus-monitor )" >> ${WATCHDOG_PID}
# Add our PID to the list of running daemons to kill
echo "$$" >> ${WATCHDOG_PID}

while read line ; do
    if [ -f ${USBWD_REBOOT_FILE} ] ; then
        # We asked for a reboot on unplug, let's see...
        if echo ${line} | grep usbPlugOut > /dev/null 2>&1 ; then
            # Yep, we're plugged out! Let's do our stuff in a locked session to avoid double-reboots...
            if ${USBWD_LOCK_BIN} -p $$ -f ${USBWD_LOCK_FILE} ; then
                # We only want to do this once, so kill the reboot file
                rm -f ${USBWD_REBOOT_FILE}
                # Log our restart
                msg "restarting framework via USB watchdog" I
                # Give us some time to settle
                sleep 10
                # Sync the disk to avoid wreaking havoc on the FS
                sync
                # And restart the framework
                /etc/init.d/framework restart
                # And then remove our lock file
                rm -rf ${USBWD_LOCK_FILE}
            else
                # Meep! We're already locked doing a reboot, something went wrong...
                msg "we're already restarting the framework via USB watchdog, go away" W
            fi
        fi
    fi
done
