#!/bin/bash

. /usr/share/PspUtils/psp_install.sh

find_kernel_param() {
   local cmdline="$1"
   local match="$2"
   while IFS='=' read -r n v; do
      case $n in
         $match) echo "$v"
      esac
   done <<< "$( echo $cmdline | tr " " "\n" )"
}

mkdir -p /mnt/flash/debug/
chmod 770 /mnt/flash/debug
echo -e "Reload requested by the user.\nrebootIsImminent" > \
         /mnt/flash/debug/local_reload_cause

# ceosKernelParamsFile is a volume mounted file containing all the expected kernel
# params. Typically these can be found in /proc/cmdline. However if cEOS was started
# from a non-Arista host, the kernel params may not be applied until the device is
# rebooted. So we volume mount the file from the host to get the necessary params.
ceosKernelParamsFile="/etc/sysconfig/kernel_inst_ceos.cfg"
export ONIE_PLATFORM
export EOS_PLATFORM
if [ ! -f "$ceosKernelParamsFile" ]; then
   echo "Could not find $ceosKernelParamsFile"
else
   . $ceosKernelParamsFile

   # EOSKERNELPARAMS is set from within the ceosKernelParamsFile
   ONIE_PLATFORM="$(find_kernel_param "$EOSKERNELPARAMS" onie_platform)"
   EOS_PLATFORM="$(find_kernel_param "$EOSKERNELPARAMS" platform)"
fi

if [ ! -z "$ONIE_PLATFORM" ]; then
   install_psp "$(find_psp_in_ceos $ONIE_PLATFORM)"
fi

# sync only waits until kernel flushes the kernel buffers to the storage device.
# However on some slow devices the device internal cache can take some more time
# to flush. A reset may cause data loss, so wait 3 seconds to be safe.
sync
sleep 3

. /usr/bin/powercycle
