#!/bin/sh

# set_wan_static_ip.sh for NON-openwrt systems
# Simplified from package_repos/dy_base-files/lib/dyiot/bin/set_wan_static_ip.sh

export PATH=/opt/lnxall_app/bin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin

help() {
    cat <<_HELP_
Setup WAN port on static ip mode.
Usage: $0 {wan|wan1|wan2} GATEWAY IPADDR/NETMASK[,IPADDR/NETMASK] DNS[,DNS] [-S] 
        -S # don't restart service
Example:
    $0 wan 172.16.139.254 172.16.139.250/255.255.255.0 8.8.8.8 -S # Set wan as static ip without default route.
    $0 wan2 10.1.1.1 10.1.1.3/255.255.255.0,10.1.1.5/255.255.255.0 114.114.114.114 -r 10.1.1.3 # Set wan2 as static ip with default route.
_HELP_
}


if [ $# -lt 4 ]; then
    help
    exit 1
fi

IFX=
NO_RESTART=
GATEWAY="$2"
IPS="$3"
DNSS="$4"

BOARD="$(cat /tmp/sysinfo/board_name)"
case "${BOARD}" in
    WLOSANY_RK3568*)
        IFX="$1"
        if [ "${IFX}" != 'wan' -a "${IFX}" != "wan1" ] ; then
            echo "Error, invalid network interface for RK3568: ${IFX}" 1>&2
            exit 1
        fi
        ;;
    WLOSANY_RK3588*)
        IFX="$1"
        if [ "${IFX}" != 'wan' -a "${IFX}" != "wan1" ] ; then
            echo "Error, invalid network interface for RK3588: ${IFX}" 1>&2
            exit 1
        fi
        ;;
    WLOSANY_EM1000)
        IFX="$1"
        ;;
    WLOSANY_X86_V3)
        IFX="$1"
        ;;
    WLOSANY_LC100)
        IFX="$1"
        if [ "${IFX}" != 'wan' ] ; then
            echo "Error, invalid network interface for LC100: ${IFX}" 1>&2
            exit 1
        fi
        ;;
    *)
        help; exit 1;;
esac
shift 4

while [ -n "$1" ]; do
    case $1 in
        -S) NO_RESTART=1 ; shift 1 ;;
        --) shift ; break ;;
        -*) help ; exit 1 ;;
        *) break ;;
    esac
done

uci delete network.${IFX}.dns 2>/dev/null
uci delete network.${IFX}.ipaddr 2>/dev/null
uci set "network.${IFX}.proto=static"
uci set "network.${IFX}.gateway=${GATEWAY}"

NETMASK=
for ip in $(echo -n "${IPS}" | sed -e 's/,/ /g') ; do
    OIFS=$IFS;IFS='/';set -- $ip;ipaddr=$1;NETMASK=$2;IFS=$OIFS
    if [ "$ipaddr" != "$src_ip" ]; then
        uci set network.${IFX}.ipaddr=$ipaddr
    fi
done
[ -n "${NETMASK}" ] && uci set "network.${IFX}.netmask=${NETMASK}"

if [ -n "${DNSS}" ] ; then
    for dns in $(echo -n "${DNSS}" | sed -e 's/,/ /g') ; do
        uci add_list "network.${IFX}.dns=$dns"
    done
fi

uci commit network
[ -z "$NO_RESTART" ] && nothup netuci
echo "Set WAN port $IFX on static ip mode"
exit 0
