#!/bin/sh
#set -x
#dmesg -n 7

. /usr/cisco/bin/ciscosetup.sh
. /usr/bin/parse_cmdline.sh


board_id="`cmdline_get_board_id`"

if [ "$MERAKI_BOARD" == "barbados" ]; then
  init_primary_phy

  # Barbados is fully supported with MFG/ACT2 device certificate
  # Remove any SSC certificates that may still be present
  [[ -f "/storage/cert.pem" ]] && rm "/storage/cert.pem"
  [[ -f "/storage/key.pem" ]] && rm "/storage/key.pem"
elif [ "$MERAKI_BOARD" == "corsica" -o "$MERAKI_BOARD" == "mallorca" -o \
       "$MERAKI_BOARD" == "axel-qca" -o "$MERAKI_BOARD" == "entr17" ]; then

    cookie_model=`cat /COOKIE_PID |cut -d '-' -f 2`
    if [ "$cookie_model" == "AP1840I" ]; then
        RADIO_FW="AR900B/hw.2"
    elif [ "$MERAKI_BOARD" == "mallorca" -o "$MERAKI_BOARD" == "entr17" ]; then
        RADIO_FW="IPQ4019/hw.1"
    elif [ "$MERAKI_BOARD" == "axel-qca" ]; then
        RADIO_FW="IPQ8074"
    else #corsica
        RADIO_FW="AR900B/hw.2"
    fi

    # Setup storage2 for backup storage
    if [ -f /etc/storage2.sh ]; then
        /etc/storage2.sh
    fi

    # this is temporarily added for QCA to test their firmware binary
    if [ -d /storage/firmware -a -d /storage/firmware/$RADIO_FW ]; then
        echo -e "\n\n ### Overwriting /lib/firmware with /storage/firmware \n\n"
        mv /lib/firmware /lib/firmware.build
        cp -a /storage/firmware lib/firmware
        mv /lib/wifi/Data.msc /lib/wifi/Data.msc.build
        cp /storage/firmware/Data.msc /lib/wifi/Data.msc
    fi

    if [ -d /storage/persist -a -d /storage/persist/ini ]; then
        if [ -f /storage/persist/ini/QCA8074V2_i.ini ]; then
            cp /storage/persist/ini/QCA8074V2_i.ini /ini/internal/QCA8074V2_i.ini
        fi
        if [ -f /storage/persist/ini/global_i.ini ]; then
            cp /storage/persist/ini/global_i.ini /ini/internal/global_i.ini
        fi
    fi

    if [ "$MERAKI_BOARD" == "corsica" -o "$MERAKI_BOARD" == "mallorca" -o \
         "$MERAKI_BOARD" == "entr17" ]; then
        # copy 5G BDF files from either ETSI or nonETSI folder
        CARRIER_OUTPUT=$(runmax 5 show_carrier_cookies)
        argsNum=$(echo $CARRIER_OUTPUT | awk -F',' '{print NF}')
        if [ $argsNum == "3" ];
        then
            domain_5g=$(echo $CARRIER_OUTPUT | awk -F',' '{print $3}')
            ETSI_domain=12
            if [ "$domain_5g" == "$ETSI_domain" ]; then
                echo "===   5G radio domain is $domain_5g, COPY 5G BDF files from ETSI_BDF folder   ==="
                cp lib/firmware/$RADIO_FW/ETSI_BDF/* lib/firmware/$RADIO_FW
            else
                echo "===   5G radio domain is $domain_5g, COPY 5G BDF files from non_ETSI_BDF folder   ==="
                cp lib/firmware/$RADIO_FW/non_ETSI_BDF/* lib/firmware/$RADIO_FW
            fi
        else
            echo "\n\n ######## Domain not available to determine ETSI   ### \n\n"
            echo "===   COPY 5G BDF files from ETSI_BDF folder   ==="
            cp lib/firmware/$RADIO_FW/ETSI_BDF/* lib/firmware/$RADIO_FW
        fi
    fi

elif [ "$MERAKI_BOARD" == "apvirtual" ]; then
    apvirtual_generate_ssc
elif [ "$MERAKI_BOARD" == "axel-bcm" ]; then
  echo 5 > /proc/sys/kernel/printk
  if [ -f /etc/init.d/axel-bcm.sh ]; then
       sh /etc/init.d/axel-bcm.sh
  fi
fi

#early memory debug staging, make sure fs already mounted before this point
if [ -f /storage/boot_dbg_cmd.sh ]; then
    sh /storage/boot_dbg_cmd.sh
fi

# Setup boot info and image version
if [ -f /usr/bin/pubfunc.sh ]; then
    . /usr/bin/pubfunc.sh
    check_flash_storage 0 # check for flash storage usage
fi
setup_boot_info

# Support user home directory
mkdir -p /storage/support/.ssh
echo '' > /storage/support/.ssh/authorized_keys
chown support /storage/support
chown support /storage/support/.ssh

# Make sure root_access_list can't be overwritten
touch /storage/config.local
touch /tmp/config.tmp

# Increment boot count.
if [ -f /storage/BOOT_COUNT ]; then
  boot_count=`board_data_config -b -a /storage/BOOT_COUNT`
  echo $boot_count > /LAST_BOOT_COUNT

  # By keeping /storage/BOOT_COUNT.reserve on the filesystem we reserve enough blocks
  # to update /storage/BOOT_COUNT even if /storage fills to capacity
  echo $(($boot_count + 1)) > /storage/BOOT_COUNT.reserve && \
      sync && \
      mv /storage/BOOT_COUNT.reserve /storage/BOOT_COUNT && \
      echo $(($boot_count + 1)) > /storage/BOOT_COUNT.reserve && \
      sync
else
  echo "1" > /storage/BOOT_COUNT
  echo "0" > /LAST_BOOT_COUNT
fi

sync

rm -rf /storage/RETRY_UPGRADE

# If rebooting 2 times into an unsafe config, revert to safe.
safe_config_file=/storage/config.safe."`cat /MERAKI_BUILD`"
if [ -f /storage/config -a -f "$safe_config_file" ] && \
    ! cmp /storage/config "$safe_config_file" >/dev/null 2>&1 && \
    grep "valid_config true" "$safe_config_file" >/dev/null 2>&1; then
    if [ -f /storage/config.unsafe ] && \
	cmp /storage/config /storage/config.unsafe >/dev/null 2>&1; then
	cp "$safe_config_file" /storage/config.new && \
	    mv /storage/config.new /storage/config
	mv /storage/config.unsafe /storage/config.try."`cat /MERAKI_BUILD`"
    else
	cp /storage/config /storage/config.unsafe
    fi
else
    rm -f /storage/config.unsafe
fi

# If too many config files (> 4 config.{try,safe}), remove random ones.
remove_extra_storage () {
    while true; do
	n=`ls /storage/$1.* 2>/dev/null | wc -l`
	if [ $n -le 4 ]; then break; fi
	rnum=`head -c 2 /dev/urandom | hexdump -v | head -n 1 | tr -d ' '`
	i=$(((0x$rnum * $n) / 65536 + 1))
	f=`ls /storage/$1.* 2>/dev/null | head -n $i | tail -n 1`
	if [ -n "$f" -a "$f" != "/storage/$1.`cat /MERAKI_BUILD`" ]; then
	    rm -f "$f"
	fi
    done
}
remove_extra_storage config.try
remove_extra_storage config.safe

if [ "$MODE" != "docker" ]; then
    sh /etc/sysdefault.sh
fi

#platform independant modules
if [ -f /lib/modules/aptrace.ko ]; then
    modload /lib/modules/aptrace.ko && modrm /lib/modules/aptrace.ko
fi

if [ "$MERAKI_BOARD" == "corsica" -o "$MERAKI_BOARD" == "mallorca" -o \
     "$MERAKI_BOARD" == "entr17" ]; then
    if [ -f /lib/modules/led_module.ko ]; then
        modload /lib/modules/led_module.ko && modrm /lib/modules/led_module.ko
    fi
    #Increase panic timeout to 15 seconds is needed to allow all CPU
    #traces to be printed on console and crash file, in case of WDT and
    #memory corruption
    echo 15 > /proc/sys/kernel/panic
fi
# board_id for milos 0x23 and duplo 0x27, must use low level this point in startup.
if [ "$board_id" == "0x23" ] || [ "$board_id" == "0x27" ]; then
    setup_led_gpio "15" "red" "out"
    setup_led_gpio "14" "green" "out"
    setup_led_gpio "13" "amber" "out"
    if [ -f /lib/modules/led_module.ko ]; then
        modload /lib/modules/led_module.ko && modrm /lib/modules/led_module.ko
    fi
fi


# Call platform specific wifi config
wifi_config

mac=$(ifconfig wired0 2>/dev/null | sed -n 's/^.*HWaddr \([0-9A-Za-z:]*\).*/\1/p')

if [ ! -f /MERAKI_SERIAL ]; then
  echo $mac | sha1sum | sed 's/^\(...\)\(...\)\(...\).*/xxx-\2-\3/' > /MERAKI_SERIAL
fi

# Generate a unique. This is for one device
if [ "$MERAKI_BOARD" == "barbados" ]; then
#MVL echo "Q2CM-9JBF-PYW8" > /MERAKI_SERIAL
echo "AIR-CAP3802E" > /MERAKI_SERIAL
fi
#

# extract the bottom three octets to use as IP
export SRCR_IP=`\`echo $mac | sed -n 's/.*:.*:.*:\([0-9A-Za-z:]*\):\([0-9A-Za-z:]*\):\([0-9A-Za-z:]*\).*/printf 6.%d.%d.%d\\\\n 0x\1 0x\2 0x\3/p'\``
export SRCR_IP6=`echo $mac | sed -n 's/\([0-9A-Za-z]*\):\([0-9A-Za-z]*\):\([0-9A-Za-z]*\):\([0-9A-Za-z]*\):\([0-9A-Za-z]*\):\([0-9A-Za-z]*\).*/printf fd0a:9b09:1f7:0:%x%x:%xff:fe%x:%x%x $((0x\1^0x2)) 0x\2 0x\3 0x\4 0x\5 0x\6/p' | xargs -0 sh -c`

echo ${SRCR_IP} > /MERAKI_IP
echo ${SRCR_IP6} > /MERAKI_IP6
if [ "$MERAKI_BOARD" == "marvell" -o "$MERAKI_BOARD" == "barbados" ]; then
    mac=`cat /MERAKI_MAC`
fi

echo ${mac} > /MERAKI_MAC

echo m$mac | sed -e 's/://g' > /proc/sys/kernel/hostname

#TODO: this function call shall be removed, after serial number issue is fixed.
create_platform_files

if [ -e  /radio_fw/txpfiles/txpinit.sh ]; then
    # set up radio tx power files for this SKU
    /radio_fw/txpfiles/txpinit.sh
fi
