#!/bin/sh

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

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

help() {
    cat <<_HELP_
Setup/Remove LAN port on static ip mode.
Support create/setup VLAN interface.
lan represents PHY port eth3. It means the native vlan.
LAN port will be added to a security zone, TRUSTED by default.

Usage:  $0 {set|del} {lan} [--ipaddr IPADDR] [--netmask NETMASK]
        $0 set {lan} --ipaddr IPADDR --netmask NETMASK [-S]
        --ipaddr IPADDR # static ipaddress
        --netmask NETMASK # format 255.255.255.0
        -S # don't restart service
Example:
    $0 set lan 192.168.254.254 255.255.255.0 # set lan port with static ip addresses
_HELP_
}

if [ "$1" != "set" ] ; then
    [ "$1" = "del" ] && exit 0
    help ; exit 1
fi
shift 1

IFX="$1"
[ "$IFX" != "lan" ] && exit 0 # terminate silently
shift 1

IPADDR=
NETMASK=
NO_RESTART=
while [ -n "$1" ]; do
    case $1 in
        --ipaddr) IPADDR="$2" ; shift 2 ;;
        --netmask) NETMASK="$2" ; shift 2 ;;
        -S) NO_RESTART='1' ; shift 1 ;;
        --) shift 1 ; break ;;
        -*) help ; exit 1 ;;
        *) shift 1 ;;
    esac
done

set_vlan() {
    [ -n "$IPADDR" -a -n "$NETMASK" ] || exit 1
    uci set network.${IFX}=interface
    uci set network.${IFX}.proto='static'
    uci set network.${IFX}.device='br-lan'
    uci set network.${IFX}.ipaddr="${IPADDR}"
    uci set network.${IFX}.netmask="${NETMASK}"
}

set_vlan
uci commit network
[ -z "$NO_RESTART" ] && nothup netuci
echo "Set IP $IPADDR/$NETMASK on $IFX"
exit 0
