#!/bin/sh

export PATH=/lib/dyiot/bin:/usr/sbin:/usr/bin:/sbin:/bin

# global variables
md5val=""
CFGDIR='/app/cfgs_jingzai'

get_md5val() {
    md5val=""
    local tfile="$1"
    if [ ! -e "${tfile}" ] ; then
        echo "Error, file does not exist: '${tfile}'" 1>&2
        return 1
    fi
    local md5_val="`md5sum ${tfile} | awk '{print $1}'`"
    if [ -z "${md5_val}" ] ; then
        echo "Error, failed to compute md5sum for '${tfile}'" 1>&2
        return 2
    fi
    md5val="${md5_val}"
    return 0
}

update_file() {
    local fsrc="$1"
    local fdst="$2"
    get_md5val "$fsrc"
    local md5val0="${md5val}"
    if [ -z "${md5val0}" ] ; then
        return 1
    fi
    get_md5val "$fdst"
    local md5val1="${md5val}"
    if [ "${md5val0}" == "${md5val1}" ] ; then
        echo "INFO: no need to update config file: '$fdst'"
        return 2
    fi
    echo "INFO: updating '$fdst'..."
    cp -f "$fsrc" "$fdst"
    return $?
}

disable_instsvr() {
    # disable superver_4g.sh
    local initd="/etc/init.d/$1"
    if [ -x "${initd}" ] ; then
        ${initd} stop >/dev/null 2>&1
        ${initd} disable >/dev/null 2>&1
    fi
    initd="$1"
    if [ -x "${initd}" ] ; then
        ${initd} stop >/dev/null 2>&1
        ${initd} disable >/dev/null 2>&1
    fi
    return 0
}

update_network() {
    update_file "${CFGDIR}/network" "/etc/config/network"
    if [ $? -eq 0 ] ; then
        /etc/init.d/network reload
        sleep 3
    fi
    return 0
}

update_ser2net() {
    local SER2NET_INIT="/etc/init.d/ser2net"
    update_file "${CFGDIR}/ser2net.conf" "/etc/ser2net.conf"
    update_file "${CFGDIR}/ser2net.init" "${SER2NET_INIT}"
    if [ $? -eq 0 ] ; then
        chmod +x "${SER2NET_INIT}"
        "${SER2NET_INIT}" enable
        "${SER2NET_INIT}" start
    elif [ -x "${SER2NET_INIT}" ] ; then
        "${SER2NET_INIT}" enable
    fi
    return 0
}

update_firewall() {
    update_file "${CFGDIR}/firewall" "/etc/config/firewall"
    [ $? -eq 0 ] && "/etc/init.d/firewall" reload
    return 0
}

delay_without_tagfile() {
    local tfile="$1"
    if [ ! -e "${tfile}" ] ; then
        touch "${tfile}"
        sleep "$2"
    fi
    return 0
}

# delay 10 seconds:
# delay_without_tagfile "/tmp/jingzai_addon" 10

disable_instsvr "rs485"
disable_instsvr "supervisor_4g"
update_network
update_ser2net
update_firewall
sync ; exit 1 # exit with non-zero status
