#!/bin/sh

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

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

help() {
    cat <<_HELP_
Setup WAN port on DHCP mode.
Usage: $0 {wan|wan1|wan2} [-d DNS[,DNS]] [-S]
        -d DNS[,DNS] # Manually add dns list
        -S # don't restart service
Example:
    $0 wan # Set port 'wan' as dhcp mode.
    $0 wan1 -d 8.8.8.8,9.9.9.9 # Set port 'wan' as dhcp mode with manual DNS settings.
_HELP_
}

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

IFX=
DNSS=
NORESTART=0
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
        ;;
    *)
        echo "Unknown board: ${BOARD}" ; help
        exit 1 ;;
esac
shift 1

while [ -n "$1" ]; do
    case $1 in
        -d) DNSS="$2" ; shift 2 ;;
        -S) NORESTART=1 ; shift 1 ;;
        *) break ;;
    esac
done

uci delete network.${IFX}.dns 2>/dev/null
uci delete network.${IFX}.ipaddr 2>/dev/null
uci delete network.${IFX}.netmask 2>/dev/null
uci delete network.${IFX}.gateway 2>/dev/null
uci set network.${IFX}.proto='dhcp'
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
[ "${NORESTART}" != "1" ] && nothup netuci
echo "Set WAN port $IFX on DHCP client mode"
exit 0
