#!/bin/bash
#
# description: Driver and kernel interfaces restore script during
# SSU reboot/ SSU hitless reboot

ssuRestoreLegacyLog=/mnt/flash/SsuRestoreLegacy.log
ssuRestoreLog=/mnt/flash/SsuRestore.log
ssuAddOnLog=/mnt/flash/SsuAddOn.log
ssuRestoreDisableFile=/mnt/flash/disable.ssurestore
asuDrvIntfSetup=/usr/bin/AsuDrvIntfSetup
asuFastPktRestore=/usr/bin/AsuFastPktRestore
convertPStore=/usr/bin/ConvertPStore
oldAfprData=/mnt/flash/.asu-reload-data.conf
asuLog=/mnt/flash/persist/AsuEvent.log

ssrLog=/mnt/flash/persist/SsrEvent.log
ssrRestoreLog=/mnt/flash/SsrRestore.log

echo -n "" >> $ssuRestoreLegacyLog
echo -n "" >> $ssuRestoreLog
timestamp() {
   date "+%F %T.%6N"
}
if cat /proc/cmdline | grep -q "arista.asu_\(reboot\|hitless\)"; then
   echo "$(timestamp) Starting SsuRestore service (SSU Reload)" >> $asuLog
elif cat /proc/cmdline | grep -q "arista.swagMode"; then
   echo "$(timestamp) Starting SsuRestore service (SSR Reload)" >> $ssrLog
else
   echo "$(timestamp) Starting SsuRestore service (Normal Reload)" >> $asuLog
fi
echo "$(timestamp) Checking if this is ssu reboot to run SsuRestore service" \
     2>&1 | tee -a $ssuRestoreLog >> $ssuRestoreLegacyLog

if [ -e $ssuRestoreDisableFile ]; then
   echo "$(timestamp) Skipping AsuFastPktRestore as $ssuRestoreDisableFile exists" | tee -a $ssuRestoreLog >> $ssuRestoreLegacyLog
   exit 0
fi
echo "$(timestamp) Converting PStore if necessary" | tee -a $ssuRestoreLog >> $ssuRestoreLegacyLog
sudo $convertPStore 2>&1 | tee -a $ssuRestoreLog >> $ssuRestoreLegacyLog
if cat /proc/cmdline | grep -q "arista.asu_\(reboot\|hitless\)"; then
    echo "$(timestamp) Running SsuRestore service" 2>&1 | tee -a $ssuRestoreLog >> $ssuRestoreLegacyLog
    # If we find the old AFPR data file, then start AsuDrvIntfSetup, else
    # run the new AFPR.
    if [ -e $oldAfprData ]; then
        if [ -x $asuDrvIntfSetup ]; then
            echo "$(timestamp) Starting AsuDrvIntfSetup" >> $ssuRestoreLegacyLog 2>&1
            sudo $asuDrvIntfSetup >> $ssuRestoreLegacyLog 2>&1
        fi
    else
        if [ -x $asuFastPktRestore ]; then
            echo "$(timestamp) Starting AsuFastPktRestore" >> $ssuRestoreLog 2>&1
            sudo $asuFastPktRestore >> $ssuRestoreLog 2>&1
        fi
    fi

    asuAddonScript=/mnt/flash/AsuAddonScript
    if [ -x $asuAddonScript ]; then
        echo "$(timestamp) Running SSU addon script" > $ssuAddOnLog 2>&1
        sudo $asuAddonScript >> $ssuAddOnLog 2>&1
        backUpAddonScript=/mnt/flash/AsuAddonScript.bak
        sudo mv $asuAddonScript $backUpAddonScript
    fi
fi

if cat /proc/cmdline | grep -q "arista.swagMode"; then
   echo "$(timestamp) Running SsuRestore service" >> $ssrRestoreLog
   if [ -x $asuFastPktRestore ]; then
      echo "$(timestamp) Starting AsuFastPktRestore" >> $ssrRestoreLog 2>&1
      sudo $asuFastPktRestore >> $ssrRestoreLog 2>&1
   fi
fi

