#!/bin/sh /etc/rc.common
#
# Copyright (C) 2014-2020, Lantronix, Inc. All Rights Reserved.
#           7535 Irvine Center Drive, Suite 100
#           Irvine, CA 92618 USA

# Permission to use, copy, modify this software for any
# purpose is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.

# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#


START=19
APP="link"
lock() {
    until [[ -f /tmp/system.initialized && -f /tmp/system.evo.initialized ]]
    do
        logger -p "user.debug" "$APP$1 $$ : waiting for system to be initialized"
        sleep 5
    done
    while true; do
        if mkdir /var/lock/$APP; then
            logger -p "user.debug" "$APP$1 $$ : lock"
            break
        else
            logger -p "user.debug" "$APP$1 $$ : wait"
            usleep 500000
        fi
    done
}

unlock() {
    logger -p "user.debug" "$APP$1 $$ : unlock"
    rm -rf  /var/lock/$APP
}

boot() {
	start
	return 0
}

start() {
    logger "link start"
    iface_type=$(uci get link.Wan.Type)
    if [ $iface_type == "Copper" ]; then
        iface_cop_speed=$(uci get link.Wan.CopperSpeed)
        
        if [ $iface_cop_speed == "Auto" ]; then
            /usr/bin/eds5klink copper autonegon &
        fi
        if [ $iface_cop_speed == "1000" ]; then
            /usr/bin/eds5klink copper autonegoff $iface_cop_speed Full &
        fi
        if [ $iface_cop_speed == "100" ]; then
            iface_duplex=$(uci get link.Wan.Duplex)
            /usr/bin/eds5klink copper autonegoff $iface_cop_speed $iface_duplex &
        fi
        if [ $iface_cop_speed == "10" ]; then
            iface_duplex=$(uci get link.Wan.Duplex)
            /usr/bin/eds5klink copper autonegoff $iface_cop_speed $iface_duplex &
        fi
    fi
    if [ $iface_type == "SFP" ]; then
        iface_sfp_speed=$(uci get link.Wan.SFPSpeed)
        if [ $iface_sfp_speed == "1000" ]; then
            /usr/bin/eds5klink sfp autonegoff $iface_sfp_speed &
        fi
        if [ $iface_sfp_speed == "100" ]; then
            /usr/bin/eds5klink sfp autonegoff $iface_sfp_speed &
        fi
    fi
}

stop() {
    logger "link stop"
    kill -9 `pidof eds5klink`
}
reload() {
    stop	
    start
}


