#!/bin/bash

veosPlatforms=( "veos" "baremetal" "councilbluffs" "independence" "willamette" )
platform=${EOS_PLATFORM:-$(xargs -n1 < /proc/cmdline |
                                 sed -n '0,/^platform=/{s/^platform=//p}')}

# This check assumes that there are no spaces in the platform name
# via /proc/cmdline and will have to change if for some reason
# this assumption changes down the line
[[ ! " ${veosPlatforms[*]} " =~ " $platform " ]] && exit 0

# This is needed to map any seriously bad cases for user to remedy.
declare -A vEosErrorTable
declare -i lastError=4 # keep in sync with the array
if [ -f "/sys/class/dmi/id/sys_vendor" ]; then
    sys_vendor=`cat /sys/class/dmi/id/sys_vendor`
fi
# This should be kept in sync with the EosCloudInit python script.
vEosErrorTable=(
[1]="Fatal error. Please try booting with at least 2 CPUs."
[2]="Fatal Error. Please try booting after reducing number of "\
"VM interfaces to <=8 due to memory limitations."
[3]="Unsupported CloudEOS platform vendor: ${sys_vendor:-unknown}, "\
"please contact Arista support."
# Add new here and bump up the last unknown one
[${lastError}]="Unknown fatal error. System halted"
)

# Caravan products will log .CloudInitLogs to /var/log/ and veos
# products will continue logging messages to /mnt/flash/.
# The reason for this is that EosCloudInitLib.py will write debug messages
# to .CloudInitLogs and if this file resides in /mnt/flash/ and /mnt/flash/
# is full EosCloudInitScript will terminate early which will then not allow
# sfe and EOS to boot properly. This isn't an issue in veos which is why
# .CloudInitLogs will remain in /mnt/flash in case veos has to mount flash
# to access the logs.
LOG_FILE=""
# We are using "grep -qE" instead of equality to check ruby and non-ruby
# since checking ruby and non-ruby with equality would require a longer command
if echo $platform | grep -qE 'willamette|independence|councilbluffs' ; then
	LOG_FILE=/var/log/.CloudInitLogs
else
	LOG_FILE=/mnt/flash/.CloudInitLogs
fi

# Redirect stdin to prevent EosInit from dropping into the debugger on failure
if /usr/bin/EosCloudInit </dev/null >>$LOG_FILE 2>&1; then
   exit 0
else
    # If EosInit fails, the system is pretty much hosed
    rc=$?
    echo "     ( EosCloudInit failure code: $rc )"
    if [ $rc -le ${lastError} ]; then
        echo "  ( ${vEosErrorTable[$rc]} )"
        echo "  ( Disabling watchdog )"
        /usr/bin/wdogdev -s
        /usr/sbin/halt --halt
    fi
    echo
    echo $"   (errors in $LOG_FILE)"
    echo $"   (Mount disk on another machine to access logs)"
    exit 1
fi

