#!/bin/sh

. /etc/PG.conf

RAMDISK="/usr/ramdisk"
FLOWEYE="${RAMDISK}/bin/floweye"

NETEV_ALARM="${RAMDISK}/bin/netev_alarm.sh"

#APP bin
APPNAME="webui"
APPROOT="${RAMDISK}/app/${APPNAME}"
APPBIN="${APPROOT}/bin"
APPLIB="${APPROOT}/lib"
CHECK_APUPGRADE="${APPBIN}/check_apupgrade"
CHECK_MESSAGE="${APPBIN}/check_message"
SAC_CRONTAB="${APPBIN}/sac_crontab"
SAC_ROAM="${APPBIN}/sac_roam"


DELAY100MS()
{
    myusleep=`which aaa 2>/dev/null`
    if [ "${myusleep}" != "" ]; then
        t=$(($1 * 100000))
        usleep $t
    else
        sleep .$1
    fi
}


v6network()
{
    v6ifadmin="${PGETC}/web/v6ifadmin.conf"

    [ "`uname`" != "Linux" ] && return
    [ ! -f ${v6ifadmin} ] && return

    . ${v6ifadmin}

    [ "${v6_ip}" = "" -o "${v6_gateway}" = "" ] && return
    
    for ip6 in `ip -6 addr show ${ADMIN_PORT} | grep inet6 | awk '{print $2}'`
    do
        ip addr del ${ip6} dev ${ADMIN_PORT}
    done

    ip -6 addr add ${v6_ip} dev ${ADMIN_PORT}
    ip -6 route del default
    ip -6 route add default via ${v6_gateway} dev ${ADMIN_PORT}
}


warring_action()
{
    for pid in `ps -axwww | grep "netev_alarm.sh" | grep -v grep | awk '{print $1}'`;
    do
        kill -9 ${pid} >/dev/null 2>&1
    done

    notify2user=`${FLOWEYE} nevt stat | grep "notify2user=" | cut -d"=" -f2`

    if [ "${1}" = "start" -a "${notify2user}" = "1" ]; then
        ${NETEV_ALARM} &
    fi
}


confsync_action()
{
    sync_conf="${PGETC}/web/config_sync.conf"
    sync_api="config_sync.cgi"
    syncd="${APPBIN}/pa_config_sync"
    api_dir="${RAMDISK}/admin/api"

    mkdir -p ${api_dir}
    [ -f ${api_dir}/${sync_api} ] && rm -rf ${api_dir}/${sync_api}

    for p in ipe_syncd pa_config_sync
    do
        for pid in `ps -axwww | grep ${p} | grep -v grep | awk '{print $1}'`;
        do
            kill -9 ${pid} >/dev/null 2>&1
        done
    done

    [ -f ${sync_conf} ] && . ${sync_conf}

    if [ "${1}" = "start" -a "${enable}" = "1" ]; then
        cp ${RAMDISK}/admin/cgi-bin/common/${sync_api} ${api_dir}/
        chmod +x ${api_dir}/*
        ${syncd} >/dev/null 2>&1 &
    fi
}


webapi_action()
{
    WEBACL="${PGETC}/web/webacl.conf"
    WEBROOT="/usr/ramdisk/admin"

    [ -f "${WEBACL}" ] && . ${WEBACL}

    if [ "${api_enable}" = "on" ]; then
        mkdir -p "${WEBROOT}/api/"
        cp "${WEBROOT}/cgi-bin/common/panabit.cgi" "${WEBROOT}/api/"
    else
        rm -rf "${WEBROOT}/api/panabit.cgi"
    fi

    if [ "${sign_query_enable}" = "1" ]; then
        mkdir -p "${WEBROOT}/api/"
        cp "${WEBROOT}/cgi-bin/common/sign_query.cgi" "${WEBROOT}/api/"
    else
        rm -rf "${WEBROOT}/api/sign_query.cgi"
    fi
}


sysname_action()
{
    _etc_dir="/usr/ramdisk/etc"

    [ -f ${_etc_dir}/sysname.inf ] && rm -rf ${_etc_dir}/sysname.inf 
    [ -f "${PGETC}/sysname.conf" ] && cp "${PGETC}/sysname.conf" ${_etc_dir}
}


sac_action()
{
    SAC_OUI=${APPLIB}/oui.txt
    PROPOOL="check_apupgrade sac_crontab sac_roam"

    for process in ${PROPOOL}
    do
        for pid in `ps -ax | grep "${process}" | grep -v grep | awk '{print $1}'`
        do
            kill -9 ${pid} >/dev/null 2>&1
        done
    done

    if [ "${1}" = "start" ]; then
        ${FLOWEYE} sacoui add file=${SAC_OUI}

        for dev in "PAP-XM320:1"
        do
            model=`echo ${dev} | cut -d":" -f1`
            wifi6=`echo ${dev} | cut -d":" -f2`

            exist="`${FLOWEYE} sac_apmodel list | grep ${model}`"
            [ "${exist}" = "" ] && ${FLOWEYE} sac_apmodel add model=${model} iswifi6=${wifi6}
        done

        ${CHECK_APUPGRADE} > /dev/null 2>&1 &
        ${SAC_CRONTAB} > /dev/null 2>&1 &
        ${SAC_ROAM} > /dev/null 2>&1 &
    fi
}


if_vrrp_action()
{
    for pid in `ps -axwww | grep "if_link_vrrp" | grep -v grep | awk '{print $1}'`;
    do
        kill -9 ${pid} >/dev/null 2>&1
    done

    if [ "${1}" = "start" ]; then
        ${APPBIN}/if_link_vrrp > /dev/null 2>&1 &
    fi
}


pamalc_monitor()
{
    for pid in `ps -axwww | grep "pa_malc_sync" | grep -v grep | awk '{print $1}'`;
    do
        kill -9 ${pid} >/dev/null 2>&1
    done

    ${APPBIN}/pa_malc_sync >/dev/null 2>&1 &
}


ping_monitor()
{
    for pid in `ps -axwww | grep "pa_pingmonitor" | grep -v grep | awk '{print $1}'`;
    do
        kill -9 ${pid} >/dev/null 2>&1
    done

    if [ "${1}" = "start" ]; then
        ${APPBIN}/pa_pingmonitor > /dev/null 2>&1 &
    fi
}


sys_new_check()
{
    for pid in `ps -axwww | grep "system_news_check" | grep -v grep | awk '{print $1}'`;
    do
        kill -9 ${pid} >/dev/null 2>&1
    done

    if [ "${1}" = "start" ]; then
        ${APPBIN}/system_news_check > /dev/null 2>&1 &
    fi
}


https_cert()
{
    USER_CERT="${PGETC}/web/admin.pem"
    DEFAULT_CERT="${APPLIB}/admin.pem"

    if [ -f "${USER_CERT}" ]; then
        cp ${USER_CERT} /usr/ramdisk/admin
        cp ${USER_CERT} ${PGPATH}/admin
    else
        cp ${DEFAULT_CERT} /usr/ramdisk/admin
        cp ${DEFAULT_CERT} ${PGPATH}/admin
    fi

    if [ "${2}" = "from_web" ]; then
        /usr/ramdisk/bin/ipectrl stop monitor
        /usr/ramdisk/bin/ipectrl start monitor
        killall ipe_httpd
    fi
}


ipdb_action()
{
    pid=`ps -axwww | grep "ipdb_monitor" | grep -v grep | awk '{print $1}'`
    kill -9 ${pid} >/dev/null 2>&1 &

    if [ "${1}" = "start" ]; then
        ${APPBIN}/ipdb_monitor > /dev/null 2>&1 &
    fi
}


cact_vmgt_action()
{
    # vMGT
    OEM=`grep "OEM" /usr/ramdisk/etc/panabit.inf   | cut -d"=" -f2`
    [ "${OEM}" != "cact" ] && return

    vmgt_conf="${PGETC}/web/vmgt.conf"

    [ ! -f ${vmgt_conf} ] && return
    [ "`uname`" != "Linux" ] && return

    . ${vmgt_conf}

    vmgt_lan=`${FLOWEYE} nat listproxy | awk '{if($5 == "vMGT")print $3}'`
    lan_mac=`${FLOWEYE} nat getproxy ${vmgt_lan} | grep ifmac | cut -d"=" -f2`
    
    ipaddr=`ip addr show vMGT | grep -v inet6 | grep "inet " | awk '{print $2}' | cut -d'/' -f1`
    if [ "${ipaddr}" != "" ]; then
        ip addr del ${ipaddr} dev vMGT
    fi

    ip link set dev vMGT up
    ip addr add ${vmgt_ip}/${vmgt_mask} dev vMGT
    ip route add ${vmgt_cloudip} via ${vmgt_lanip}
    arp -s ${vmgt_cloudip} ${lan_mac}
}


ctel_vmgt_action()
{
    OEM=`grep "OEM" /usr/ramdisk/etc/panabit.inf   | cut -d"=" -f2`
    [ "${OEM}" != "pa" ] && return

    VMGT_CONF="${PGETC}/web/vmgt.conf"

    if [ "`uname`" = "Linux" ]; then
        mac=`ifconfig vMGT 2>/dev/null | grep HWaddr | awk '{print $NF}'`
    else
        mac=`ifconfig vMGT 2>/dev/null | grep ether | awk '{print $NF}'`
    fi

    [ "${mac}" = "" ] && return
    
    if [ ! -f ${VMGT_CONF} ]; then
        mkdir -p ${PGETC}/web
        echo "ip=192.168.200.200" > ${VMGT_CONF}
        echo "mask=255.255.255.0" >> ${VMGT_CONF}
        echo "gateway=192.168.200.1" >> ${VMGT_CONF}
    fi
    
    . ${VMGT_CONF}

    oldip=`ip addr show vMGT | grep -v inet6 | grep "inet " | awk '{print $2}' | cut -d'/' -f1`
    [ "${oldip}" != "" ] && ip addr del dev vMGT ${oldip}

    ip addr add dev vMGT ${ip}/${mask}
    ip link set dev vMGT up
    ip route del default 2>&1
    ip route add default via ${gateway} >/dev/null

    exist=`${FLOWEYE} nat getproxy vMGT | grep proxyid | cut -d"=" -f2`

    if [ "${exist}" != "" ]; then
        ${FLOWEYE} nat setrtif name=vMGT ifname=vMGT addr=${gateway} mask=${mask}
    else
        ${FLOWEYE} nat addrtif name=vMGT ifname=vMGT addr=${gateway} mask=${mask}
    fi

    # /༭ ˿ӳ/· by vMGT_Group
    wan_num=`${FLOWEYE} nat listproxy type=wan | awk 'END{print NR}'`
    if [ ${wan_num} -gt 0 ]; then
        ${FLOWEYE} wangroup add name=vMGT_Group type=srcdst
        wgrp_id=`${FLOWEYE} wangroup list | grep "vMGT_Group" | cut -d" " -f1`
        
        for name in `${FLOWEYE} nat listproxy type=wan | cut -d" " -f3`
        do
            ${FLOWEYE} wangroup set id=${wgrp_id} proxy=${name} weight=1
        done

        oldid=`${FLOWEYE} nat listportmap | grep vMGT_Group | grep 443 | cut -d" " -f1`
        if [ "${oldid}" != "" ]; then
            ${FLOWEYE} nat setportmap id=${oldid} wan=_wg.vMGT_Group port=443 proto=tcp mapip=${ip} mapport=443 note=豸ʹã༭
        else
            ${FLOWEYE} nat addportmap wan=_wg.vMGT_Group port=443 proto=tcp mapip=${ip} mapport=443 note=豸ʹã༭
        fi

        oldid=`${FLOWEYE} route list | grep vMGT_Group | cut -d" " -f1`
        if [ "${oldid}" != "" ]; then
            ${FLOWEYE} route set id=1 src=${ip} action=nat-_wg.vMGT_Group desc=豸ʹã༭
            ${FLOWEYE} route set id=2 dst=${ip} action=route-vMGT desc=豸ʹã༭
        else
            ${FLOWEYE} route add id=1 src=${ip} action=nat-_wg.vMGT_Group desc=豸ʹã༭
            ${FLOWEYE} route add id=2 dst=${ip} action=route-vMGT desc=豸ʹã༭
        fi
    fi
}


alwy_vmgt_action()
{
    OEM=`grep "OEM" /usr/ramdisk/etc/panabit.inf   | cut -d"=" -f2`
    [ "${OEM}" != "wy" ] && return

    VMGT_CONF="${PGETC}/web/vmgt.conf"

    if [ "`uname`" = "Linux" ]; then
        mac=`ifconfig vMGT 2>/dev/null | grep HWaddr | awk '{print $NF}'`
    else
        mac=`ifconfig vMGT 2>/dev/null | grep ether | awk '{print $NF}'`
    fi

    [ "${mac}" = "" ] && return
    
    if [ ! -f ${VMGT_CONF} ]; then
        mkdir -p ${PGETC}/web
        echo "ip=192.168.200.200" > ${VMGT_CONF}
        echo "mask=255.255.255.0" >> ${VMGT_CONF}
        echo "gateway=192.168.200.1" >> ${VMGT_CONF}
    fi
    
    . ${VMGT_CONF}

    oldip=`ip addr show vMGT | grep -v inet6 | grep "inet " | awk '{print $2}' | cut -d'/' -f1`
    [ "${oldip}" != "" ] && ip addr del dev vMGT ${oldip}

    ip addr add dev vMGT ${ip}/${mask}
    ip link set dev vMGT up

    exist=`${FLOWEYE} nat getproxy vMGT | grep proxyid | cut -d"=" -f2`

    if [ "${exist}" != "" ]; then
        ${FLOWEYE} nat setrtif name=vMGT ifname=vMGT addr=${gateway} mask=${mask}
    else
        ${FLOWEYE} nat addrtif name=vMGT ifname=vMGT addr=${gateway} mask=${mask}
    fi

    # /༭ ˿ӳ/· by vMGT_Group
    wan_num=`${FLOWEYE} nat listproxy type=wan | awk 'END{print NR}'`
    if [ ${wan_num} -gt 0 ]; then
        ${FLOWEYE} wangroup add name=vMGT_Group type=srcdst
        wgrp_id=`${FLOWEYE} wangroup list | grep "vMGT_Group" | cut -d" " -f1`
        
        for name in `${FLOWEYE} nat listproxy type=wan | cut -d" " -f3`
        do
            ${FLOWEYE} wangroup set id=${wgrp_id} proxy=${name} weight=1
        done

        oldid=`${FLOWEYE} nat listportmap | grep vMGT_Group | grep 443 | cut -d" " -f1`
        if [ "${oldid}" != "" ]; then
            ${FLOWEYE} nat setportmap id=${oldid} wan=_wg.vMGT_Group port=443 proto=tcp mapip=${ip} mapport=443 note=豸ʹã༭
        else
            ${FLOWEYE} nat addportmap wan=_wg.vMGT_Group port=443 proto=tcp mapip=${ip} mapport=443 note=豸ʹã༭
        fi

        oldid=`${FLOWEYE} route list | grep vMGT_Group | cut -d" " -f1`
        if [ "${oldid}" != "" ]; then
            ${FLOWEYE} route set id=1 src=${ip} action=nat-_wg.vMGT_Group desc=豸ʹã༭
            ${FLOWEYE} route set id=2 dst=${ip} action=route-vMGT desc=豸ʹã༭
        else
            ${FLOWEYE} route add id=1 src=${ip} action=nat-_wg.vMGT_Group desc=豸ʹã༭
            ${FLOWEYE} route add id=2 dst=${ip} action=route-vMGT desc=豸ʹã༭
        fi
    fi
}


common_vmgt_action()
{
    [ `uname` != "Linux" ] && return
	have_kni=`ip link list | grep -E "vMGT1|vMGT0"`
    [ "${have_kni}" = "" ] && return

    if [ -f "${PGETC}/web/common_vmgt_vMGT0.conf" ]; then
        . ${PGETC}/web/common_vmgt_vMGT0.conf
        oldip=`ip addr show vMGT0 | grep -v inet6 | grep "inet " | awk '{print $2}' | cut -d'/' -f1`
        [ "${oldip}" != "" ] && ip addr del dev vMGT0 ${oldip}

        ip addr add dev vMGT0 ${ip}/${mask}
        ip link set dev vMGT0 up

        if [ "${as_default}" = "on" ]; then
            ip route del default 2>&1
            ip route add default via ${gateway} >/dev/null
        else
            for ips in `echo "${route}" | tr "," " "`
            do
                ip route add ${ips} via ${gateway} dev vMGT0
            done
        fi

        # LANӿ
        exist=`${FLOWEYE} nat getproxy vMGT0 | grep proxyid | cut -d"=" -f2`

        if [ "${exist}" != "" ]; then
            ${FLOWEYE} nat setrtif name=vMGT0 ifname=vMGT0 addr=${gateway} mask=${mask}
        else
            ${FLOWEYE} nat addrtif name=vMGT0 ifname=vMGT0 addr=${gateway} mask=${mask}
        fi

        # /༭ ˿ӳ/· by vMGT_Group
        wan_num=`${FLOWEYE} nat listproxy type=wan | awk 'END{print NR}'`
        if [ ${wan_num} -gt 0 ]; then
            ${FLOWEYE} wangroup add name=vMGT_Group type=srcdst
            wgrp_id=`${FLOWEYE} wangroup list | grep "vMGT_Group" | cut -d" " -f1`
            
            for name in `${FLOWEYE} nat listproxy type=wan | cut -d" " -f3`
            do
                ${FLOWEYE} wangroup set id=${wgrp_id} proxy=${name} weight=1
            done

            oldid=`${FLOWEYE} nat listportmap | grep vMGT_Group | grep 443 | cut -d" " -f1`
            if [ "${oldid}" != "" ]; then
                ${FLOWEYE} nat setportmap id=${oldid} wan=_wg.vMGT_Group port=443 proto=tcp mapip=${ip} mapport=443 note=豸ʹã༭
            else
                ${FLOWEYE} nat addportmap wan=_wg.vMGT_Group port=443 proto=tcp mapip=${ip} mapport=443 note=豸ʹã༭
            fi

            oldid=`${FLOWEYE} route list | grep vMGT_Group | cut -d" " -f1`
            if [ "${oldid}" != "" ]; then
                ${FLOWEYE} route set id=1 src=${ip} action=nat-_wg.vMGT_Group desc=豸ʹã༭
                ${FLOWEYE} route set id=2 dst=${ip} action=route-vMGT0 desc=豸ʹã༭
            else
                ${FLOWEYE} route add id=1 src=${ip} action=nat-_wg.vMGT_Group desc=豸ʹã༭
                ${FLOWEYE} route add id=2 dst=${ip} action=route-vMGT0 desc=豸ʹã༭
            fi
        fi
    fi

    if [ -f "${PGETC}/web/common_vmgt_vMGT1.conf" ]; then
        . ${PGETC}/web/common_vmgt_vMGT1.conf
        oldip=`ip addr show vMGT1 | grep -v inet6 | grep "inet " | awk '{print $2}' | cut -d'/' -f1`
        [ "${oldip}" != "" ] && ip addr del dev vMGT1 ${oldip}

        ip addr add dev vMGT1 ${ip}/${mask}
        ip link set dev vMGT1 up

        if [ "${as_default}" = "on" ]; then
            ip route del default 2>&1
            ip route add default via ${gateway} >/dev/null
        else
            for ips in `echo "${route}" | tr "," " "`
            do
                ip route add ${ips} via ${gateway} dev vMGT1
            done
        fi
    fi
}


sac_upgrade_server()
{
    conf="${PGETC}/web/sac_upgrade_server.conf"

    [ ! -f ${conf} ] && return

    server_enable=`grep "enable" ${PGETC}/web/sac_upgrade_server.conf | cut -d"=" -f2`

    for pid in `ps -axwww | grep ipe_httpd | grep sac | awk '{print $1}'`
    do
        kill -9 ${pid}
    done

    if [ "${server_enable}" = "1" ]; then
        /usr/ramdisk/bin/ipe_httpd -u root -p 65480 -d ${DATAPATH}/sac -M 1 -noauth 2>&1 >/dev/null
    fi
}


weboem_copy()
{
    if [ -d ${PGETC}/web/admin ]; then
        cp -Rf ${PGETC}/web/admin/* /usr/ramdisk/admin/
        cp -Rf ${PGETC}/web/admin/* /usr/system/admin/
    fi
}


set_power()
{
    # Stop datamon and save data.
    # Wait for datamon to exit.
    exited=0
    for loop in 1 2; do
        # stop datamon
        errmsg=`/usr/ramdisk/bin/ipectrl stop datamon`
        # wait datamon to exit
        count=20
        while [ ${count} -gt 0 ]; do
            sleep .5
            datamon=`ps ax | grep ipe_datamon | grep -v grep`
            if [ "${datamon}" = "" ]; then
                exited=1
                break
            fi
            count=$((${count} - 1))
        done

        [ ${exited} -eq 1 ] && break
    done

    sync
    sync

    sleep 5

    if [ "${1}" = "reboot" ]; then
        reboot
    elif [ "${1}" = "shutdown" ]; then
        if [ "`uname`" = "Linux" ]; then
            if [ "`uname -m`" = "aarch64" ]; then
                poweroff
            else
                shutdown -h now
            fi
        else
            shutdown -p now
        fi
    fi
}


notice_message_action()
{
    # stop 
    for pid in `ps -ax | grep "check_message" | grep -v grep | awk '{print $1}'`
    do
        kill -9 ${pid} >/dev/null 2>&1
    done

    # start
    [ "${1}" = "stop" ] && return

    ${CHECK_MESSAGE} > /dev/null 2>&1 &
}

# APP API
app_action()
{
    case "${2}" in
    "v6network")
        v6network
        ;;

    "warring")
        warring_action $1
        ;;

    "confsync")
        confsync_action $1
        ;;

    "webapi")
        webapi_action $1
        ;;

    "sac")
        sac_action $1
        ;;

    "if_vrrp")
        if_vrrp_action $1
        ;;

    "pamalc_monitor")
        pamalc_monitor $1
        ;;
        
    "ping_monitor")
        ping_monitor $1
        ;;

    "https_cert")
        https_cert $1
        ;;

    "sys_new_check")
        sys_new_check $1
        ;;

    "ctel_vmgt")
        ctel_vmgt_action $1
        ;;

    "cact_vmgt")
        cact_vmgt_action $1
        ;;

    "common_vmgt")
        common_vmgt_action $1
        ;;

    "sac_upgrade_server")
        sac_upgrade_server $1
        ;;

    *)
        v6network
        weboem_copy
        warring_action $1
        confsync_action $1
        webapi_action $1
        sac_action $1
        if_vrrp_action $1
        pamalc_monitor $1
        ping_monitor $1
        https_cert $*
        sys_new_check $1
        ipdb_action $1
        ctel_vmgt_action $1
        alwy_vmgt_action $1
        cact_vmgt_action $1
        common_vmgt_action $1
        sac_upgrade_server $1
        notice_message_action $1
        ;;
    esac
}


case "$1" in
    "start")
        shift
        # wait panaos
        active=0
        count=60
        while [ ${count} -ge 0 ]; do
            active=`${FLOWEYE} config stat | grep "^cfgload=" | cut -d'=' -f2`
            [ "${active}" = "1" ] && break
            DELAY100MS 5
            count=$((${count} - 1))
        done
        app_action "start" $*
        ;;

    "stop")
        shift
        app_action "stop" $*
        ;;

    "set_power")
        shift
        set_power $*
        ;;

    *)
        echo "$0 [start/stop]"
        ;;
esac
