#!/bin/sh

url="rigadogateway.com"

get_fuse () {
    local name=$1
    local pad=$2
    # read the fuse and pad the left with zeros to the size of $pad
    local fuse="0000000000"$(cat /sys/fsl_otp/$name | cut -b 3-)
    len=$(( ${#fuse} - $pad ))
    echo ${fuse:$len}
}

get_sn () {
    local base=$1
    local arena=$(get_fuse HW_OCOTP_GP$base 7)
    if [[ ${arena:0:2} == "00" ]] ; then
        # starts with "00", so doesn't start with ascii hex value
        arena=${arena:2}
    else
        # doesn't start with "00", so starts with ascii hex value
        arena=$(printf "\x${arena:0:2}${arena:2}")
    fi

    local build=$(get_fuse HW_OCOTP_GP$(( $base + 1)) 4)
    local unit=$(get_fuse HW_OCOTP_GP$(( $base + 2)) 5)

    echo "$arena$build-$unit"
}

#Read create custom serial number from fuses
get_custom_sn() {
    local fuse_70=`cat /sys/fsl_otp/HW_OCOTP_GP70`
    local fuse_71=`cat /sys/fsl_otp/HW_OCOTP_GP71`
    local fuse_72=`cat /sys/fsl_otp/HW_OCOTP_GP72`
    local strhex

    #Check for  empty fuse bank
    if [ ${fuse_72} != "0x0" ]; then
       strhex=${fuse_72:2:8}
    fi

    #Check for empty fuse bank
    if [ ${fuse_71} != "0x0" ]; then
       strhex=${strhex}${fuse_71:2:8}
    fi

    strhex=${strhex}${fuse_70:2:8}

    local i=1
    max=$(( ${#strhex} + 1 ))

    #convert hex string to ascii string
    while [ $i -lt $max ]
    do
            hex='\x'`echo $strhex | cut -c $i-$(( i + 1 ))`
            custom_sn=$custom_sn$hex
            i=$(( i + 2 ))
    done

    echo -e $custom_sn
}

if [[ "$(cat /sys/fsl_otp/HW_OCOTP_GP70)" != "0x0" ]] ; then
    hostname $(get_custom_sn)
elif [[ "$(cat /sys/fsl_otp/HW_OCOTP_GP37)" == "0x0" ]] ; then
    # No unit serial number set, use board serial number
    hostname $(get_sn 34).$url
else
    # unit serial number set, use it
    hostname $(get_sn 37).$url
fi

#Add 127.0.0.0 entry to /etc/hosts if it is not already present
grep "127.0.0.0" /etc/hosts > tmp/junk
if [ -s /tmp/junk ]; then
	rm /tmp/junk
else
        NAME=$(hostname)                                                        
        SHORTNAME=$(hostname | cut -b -16)                                      
        NEWLINE="127.0.0.0	$NAME	$SHORTNAME"                             
        sed -e"/^127.0.0.1/a ${NEWLINE}" /etc/hosts > /tmp/hosts2   
        mv /tmp/hosts2 /etc/hosts                                   
fi          
