#!/bin/sh

WDOG_FILE=/storage/watchdog_last.status
RELOAD_REASON=""

# This code is relevant only for systemd enabled platforms. When busybox
# is used it is done from the halt code in busybox.
#
# Check for "-r <reason>" and for "-d <sec>. We only need to parse the
# proper reason string and use it. We never need to send these arguments
# to the systemd backend
#
schedule_delayed_reload ()
{
    while getopts d:r: opt; do
        if [ "$opt" == "d" ]; then
            RELOAD_SECS=$OPTARG
        fi
    done

    if [ "$RELOAD_SECS" != "" ]; then
        RELOAD_TIME=`expr $RELOAD_SECS / 60`
        /bin/sh -c "nohup /sbin/shutdown -r $RELOAD_TIME > /dev/null 2>&1" &
        exit 0
    fi
}

set_reboot_reason()
{
    while getopts d:r: opt; do
      case $opt in
        r) RELOAD_REASON="$OPTARG";;
        d) ;;
        *) echo "Unknown reload argument: $OPTARG";
      esac
   done

    #If the file exists and relaod reason is same then bail out
    if [ -f $WDOG_FILE ]; then
       file_reason=`cat $WDOG_FILE | cut -d ':' -f2,3`
       if [ "$file_reason" == "$RELOAD_REASON" ]; then
           return
       fi
    fi

    if [ "$RELOAD_REASON" == "" ]; then
        RELOAD_REASON="sbin_reboot"
    fi

    echo reason: $RELOAD_REASON >> $WDOG_FILE
    #Sync the write to file system before reboot
    sync
    sync
}

systemd_reboot ()
{
    schedule_delayed_reload "$@"

    # No need to pass in any parameters
    nohup `/sbin/systemd-reboot` 2> /dev/null &

    # For some reason traditional reboot didnt go through.
    # Force reboot
    nohup `sleep 20 && /sbin/systemd-reboot -f` 2> /dev/null &
}

#Notify NBAR to STOP processing packets.
if [ -f /click/cli_h/nbar2/ap_rebooting_status ]; then
    nohup `echo 1 > /click/cli_h/nbar2/ap_rebooting_status && sleep 1` 2> /dev/null &
fi

set_reboot_reason "$@"
# First check if this is a platform that supports systemd
[ -x /sbin/systemd-reboot ] && [ -x /sbin/shutdown ] && systemd_reboot "$@"

nohup `sleep 30 && echo b > /proc/sysrq-trigger` 2> /dev/null &
sleep 30
