#! /bin/sh

# help do swith PHY

. /lib/functions.sh

sw_allow_eapol() { return 0; }
sw_restore_eapol() { return 0; }

. /lib/xq-misc/phy_switch.sh

usage () {
    echo "control phy swith"
    echo "$0 start"
    echo "$0 stop"
    echo "$0 restart"
    echo "$0 gwan - get wan speed"
    echo "$0 swan [1000|100|10] - set wan speed"
    exit 1
}

phy_stop_lan() {
    sw_stop_lan
    return $?
}

phy_start_lan() {
    sw_start_lan
    return $?
}

# make client resend DHCP request
phy_restart_lan() {
    phy_stop_lan || return 1
    sleep 3
    phy_start_lan || return 1
    return 0
}

phy_get_wan_speed() {
    if sw_is_wan_giga; then
	echo "1000Mb"
	return 0
    fi
    if sw_is_wan_100m; then
	echo "100Mb"
    else
	echo "10Mb"
    fi
    return 1
}

phy_set_wan_speed() {
    [ -z "$1" ] && echo "set speed value!" && return 1
    speed="$1"
    shift
    case "$speed" in
	10)
	    sw_set_wan_100m 10
	    sw_set_wan_giga off
	    ;;
	100)
	    sw_set_wan_100m 100
	    sw_set_wan_giga off
	    ;;
	1000)
	    sw_set_wan_giga on
	    ;;
	*)
	    echo "unsupport speed!"
	    return 1
	    ;;
    esac
    # issue re-negotiat
    if sw_reneg_wan; then
	# let phy do re-neg
	[ -z "$1" ] && sleep 2
	echo "set WAN speed to ${speed}Mb"
	return 0
    else
	ehco 'renegotiation fail!'
	return 1
    fi
}

case "$1" in
    stop)
	phy_stop_lan
    ;;
    start)
	phy_start_lan
    ;;
    restart)
	phy_restart_lan
        exit $?
    ;;
    gwan)
	phy_get_wan_speed
    ;;
    swan)
	shift
	phy_set_wan_speed "$1"
	;;
    set_eap)
	sw_allow_eapol
	;;
    del_eap)
	sw_restore_eapol
	;;
    *)
	usage
    ;;
esac
exit "$?"
