RESOLV_CONF="/ram/resolv.conf"
NTPCONFDEF="/etc/ntp/ntpd.conf.def"
NTPCONF="/ram/ntp/ntpd.conf"
TZCONF="/ram/timezone"
LTCONF="/ram/localtime"
IPC_SIMPLE_PIPE=/ram/ipc-simple-pipe
RDIR_APP="/usr/local/share/app/bin/rdir.sh"
vend_dev="/dev/block/mmc0/by-name/bootloader"         #MAG424
SYMLINKS_DIR="/dev/block/mmc0/by-name"
vend_dev_shadow="bootloader.shadow"

source /etc/init.d/splash-config.sh

DEBUG_GLOBALS=""
if [ -f /ram/debug ]; then
    DEBUG="1"
    DEBUG_GLOBALS="G"
fi

string_contain() { [ -z "${1##*$2*}" ]; }

exclude()
{
    if [ ! -f $1 ]; then
        return;
    fi
    A=`awk '{ if( index($0,"#'"$2"'") == 0 ) { print $0; }}' $1`
    echo "${A}" > $1
}

excludeRaw()
{
    if [ ! -f $1 ] || [ -z $2 ]; then
        return;
    fi
    A=`awk '{ if( index($0,"'"$2"'") == 0 ) { print $0; }}' $1`
    echo "${A}" > $1
}

selectByJsonPair()
{
    if [ ! -f $1 ] || [ -z $2 ]; then
        return;
    fi
    awk -vvar1=${2} '{ if( index($0,var1) != 0 ) { print $0; }}' $1
}

excludeByJsonPair()
{
    if [ ! -f $1 ] || [ -z $2 ]; then
        return;
    fi
    awk -vvar1=${2} '{ if( index($0,var1) == 0 ) { print $0; }}' $1
}

getMountPointByDevPath()
{
    A=$(selectByJsonPair ${MOUNTS_CACHE} "\"devPath\":\"${1}\"")
    cnt=`echo "${A}" | wc -l`
    if [ "$cnt" != "1" ]; then
        return
    fi
    echo "$A" | sed -n 's/^.*"mountPath":"\(.*\)",.*$/\1/pg'
}

excludeByDevPath()
{
    A=$(excludeByJsonPair ${1} "\"devPath\":\"${2}\"")
    echo "${A}" > ${1}
}

isNfsMount()
{
    if [ `cat /proc/cmdline | grep nfsroot | wc -l` == "1" ]; then
        export $1="y"
    else
        export $1="n"
    fi

    return
}

log()
{
    echo "$(date +%H:%M.%S) [$(basename "$0")] $1"

    if [ "$DEBUG" != "1" ] && [ -z "$DEBUG_GLOBALS" ]; then
        return
    fi

    if [ ! -d /var/logs/ ]; then
        return
    fi

    if [ -z "$LOG_FILE" ]; then
        LOG_FILE="/var/logs/$(basename "$0").log"
    fi

    if [ -n "$DEBUG_GLOBALS" ]; then
        echo "$(date +%H:%M.%S) [$DEBUG_GLOBALS][$(basename "$0")] $1" >> $LOG_FILE
    else
        echo "$(date +%H:%M.%S) [$(basename "$0")] $1" >> $LOG_FILE
    fi
}

get_nvram_env()
{
    tmpVal=`fw_printenv $1 2>/dev/null`
    FW_ENV_RESULT=${tmpVal#*=}
}

read_nvram_var()
{
    get_nvram_env $1
    echo "$FW_ENV_RESULT"
}

get_fw_env()
{
    val=`fw_printenv $1 2>/dev/null`
    export $2="${val#$1=}"
}

set_fw_env()
{
    fw_setenv $1 $2 2>&1 >/dev/null
}

ipc_invoke()
{
    echo "$1" > $IPC_SIMPLE_PIPE
}

# appending config line to current NTP config. 
# create default config if file not found
append_ntp_config()
{
    if [ ! -f $NTPCONF ]; then
        cat $NTPCONFDEF > $NTPCONF
        ARG1=$1
	IFS=' '
        set -- $(read_nvram_var "ntpurl")
        NTP_IP=$(for i; do printf "server $i #manual\n"; done)
        if [ "$NTP_IP" != "" ]; then
            echo $NTP_IP >> $NTPCONF
        fi

	#because of set spoil arg order
        echo "# $ARG1" >> $NTPCONF
    fi
}

# update default gateways for interface "$1" with new default gw list "$2" using metric "$3"
update_default_gw_for_interface()
{
    if [ -n "$2" ]; then

        # get currently active routers
        WORK_ROUTERS=`ip route | sed -n "s/^default via \([^ ]*\) dev ${1}.*$/\1/p"`
        #log "WORK_ROUTERS = ${WORK_ROUTERS}"

        # list of routers to delete
        ROUTERS_TO_DEL="";
        for i in $WORK_ROUTERS
        do
            isFound="0"
            #checking work router
            for j in $2
            do
                #compape with new router
                if [ "${i}" = "${j}" ]; then
                    isFound="1"
                    break
                fi
            done

            if [ "$isFound" = "0" ]; then
                #store router $i for deletion
                ROUTERS_TO_DEL="${ROUTERS_TO_DEL}${i} "
            fi
        done

        # add new routers
        for i in ${2}
        do
            #add router $i
            #log "add default gw ${i}, ${1}, ${3}"
            /sbin/route add default gw ${i} dev ${1} metric ${3}
        done

        # delete unneeded routers
        for i in $ROUTERS_TO_DEL
        do
            #DEL router ${i}
            #log "del default gw ${i}"
            /sbin/route del default gw ${i}
        done
    fi
}

get_file_size() {
    size=`stat -c %s $1 2>/dev/null`
    size=$((size))
    export $2=$size
}

get_flash_type() {
    mtd_num=$(cat /proc/mtd | grep -v erasesize | wc -l)
    if [ $mtd_num -gt 0 ] ; then
        export $1="nand"
    else
        export $1="mmc"
    fi
}

#MAG42x
get_name_and_len_part() {
# [in]  $1 - user-friendly partition name, e.g. "bootloader" or "logo"
# [out] $2 - size of the given partition
# [out] $3 - physical device name of given partition

    get_flash_type flash_type
    if [ "$flash_type" == "nand" ]; then
        str=`grep \"$1\" /proc/mtd`
        name=`echo "${str}" | grep -oE 'mtd[0-9]{1,}'`
        len=`echo "${str}" | awk '{print $2}'`
        if [ "$len" != "" ]; then len=$((0x${len})); fi # convert to decimal
        if [ "$1" == "bootloader" ] ; then
            name=$vend_dev_shadow
            len=`stat -c %s /dev/$vend_dev_shadow`
        fi
        export $2=$len
        export $3=$name
    elif [ "$flash_type" == "mmc" ]; then
        link_path=$SYMLINKS_DIR/$1
        full_path=$(readlink -n $link_path)
        name=$(basename $full_path)
        len=`cat /sys/class/block/${name}/size 2>/dev/null`
        export $2=$((len*512))
        export $3=$name
    fi
}

check_nand_vendor_section()
{
    rm $SYMLINKS_DIR/bootloader
    /bin/ln -s /dev/$vend_dev_shadow $SYMLINKS_DIR/bootloader
    chmod a+r /dev/$vend_dev_shadow
}

get_hwver() {
    get_name_and_len_part "bootloader" offs name
    tmp=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-32)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp
}

get_model_ext() {
    get_name_and_len_part "bootloader" offs name
    tmp1=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-64)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp1
}

get_model() {
    get_name_and_len_part "bootloader" offs name
    tmp1=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-64)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp1
}

get_vendor() {
    get_name_and_len_part "bootloader" offs name
    tmp=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-96)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp
}

get_eth_mac() {
    get_name_and_len_part "bootloader" offs name
    tmp=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-128)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp
}

get_serial() {
    get_name_and_len_part "bootloader" offs name
    tmp=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-160)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp
}

get_wifi_mac() {
    get_name_and_len_part "bootloader" offs name
    tmp=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-192)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp
}

get_bt_mac() {
    get_name_and_len_part "bootloader" offs name
    tmp=`dd if=/dev/$name bs=1 count=32 skip=$(($offs-224)) 2>/dev/null | strings -n1 | awk '{printf("%s",$0); exit;}'`
    export $1=$tmp
}

read_opkey_from_vs() {
    get_name_and_len_part "bootloader" offs name
    offs=$(($offs-11264))
    flag=`hexdump -e '1/ "%d"' -s $offs -n 4 /dev/$name`
    if [ "$flag" -ne "0" ]; then
        echo -n `dd if=/dev/$name bs=1 count=4096 skip=$offs 2>/dev/null` > $1
    else
        echo -n "" > $1
    fi
}

load_hdcp1x_from_vs() {
    get_name_and_len_part "bootloader" offs name
    addr=$(($offs-7168))
    offs=$(($offs-236))
    len=`hexdump -e '1/ "%d"' -s $offs -n 4 /dev/$name`
    dd if=/dev/$name of=$1 skip=$addr bs=1 count=$len > /dev/null 2>&1
}

load_hdcp2x_from_vs() {
    get_name_and_len_part "bootloader" offs name
    addr=$(($offs-5120))
    offs=$(($offs-232))
    len=`hexdump -e '1/ "%d"' -s $offs -n 4 /dev/$name`
    dd if=/dev/$name of=$1 skip=$addr bs=1 count=$len > /dev/null 2>&1
}

get_sdio_wifi()
{
    UNISOC_SDIO_BUS="/sys/bus/mmc/devices/sdio:8800/sdio:8800:1"
    REALTEK_SDIO_BUS="/sys/bus/mmc/devices/sdio:0001/sdio:0001:1"
    if [ -e /sys/bus/sdio/devices/mmc2* ] ; then
        UNISOC_SDIO_BUS="/sys/bus/sdio/devices/mmc2:8800:1"
        REALTEK_SDIO_BUS="/sys/bus/sdio/devices/mmc2:0001:1"
    else
        export $1="none"
        return
    fi

    if [ "${UNISOC_SDIO_BUS}" != "" ] && [ -d "${UNISOC_SDIO_BUS}" ] ; then
        export $1="sprd"
        return
    fi

    if [ "${REALTEK_SDIO_BUS}" != "" ] && [ -d "${REALTEK_SDIO_BUS}" ] ; then
        vendor=$(cat "$REALTEK_SDIO_BUS/vendor" 2>/dev/null)
        device=$(cat "$REALTEK_SDIO_BUS/device" 2>/dev/null)
        if  [ "$vendor" == "0x024c" ] && [ "$device" == "0xc822" ]; then
            export $1="rtk"
            return
        fi
        if  [ "$vendor" == "0x024c" ] && [ "$device" == "0xc821" ]; then
            export $1="rtk_8821"
            return
        fi
    fi
    export $1="unknown"
}
