#!/bin/sh

DAEMON="network-link-up"

# shellcheck source=/dev/null
[ -r "/etc/default/$DAEMON" ] && . "/etc/default/$DAEMON"


# Function to check if eth0 is UP
check_eth0_up() {
    ip link show eth0 | grep -q "state UP"
}

# Function to check for NO-CARRIER on eth0
check_no_carrier() {
    ip link show eth0 | grep -q "NO-CARRIER"
}

# Function to set eth0 up
set_eth0_up() {
    
    echo "Setting eth0 is DOWN"
    ip link set eth0 down
    ip link show eth0
    echo "Sleeping for 30 seconds..."
    sleep 30

    echo "Setting eth0 is UP"
    ip link set eth0 up
    ip link show eth0
    #echo "Sleeping for 30 seconds..."
    #sleep 30
    #ip link show eth0

    # Set timeout for eth0 to become UP (30 seconds)
    eth0_up_timeout=30
    eth0_up_counter=0
    while [ $eth0_up_counter -lt $eth0_up_timeout ]; do
        if check_eth0_up; then
            echo "eth0 is UP"
            break
        fi
        echo "Waiting for eth0 to become UP... ($eth0_up_counter)"
        sleep 1
        let "eth0_up_counter+=1"
    done

    ip link show eth0
}

start() {
    ip link set eth0 up
    sleep 2
    ip link show eth0
    no_carrier_timeout=4
    no_carrier_counter=0
    while [ $no_carrier_counter -lt $no_carrier_timeout ]; do
        if check_no_carrier; then
            echo "NO-CARRIER is present on eth0. Continuing to wait..."
            set_eth0_up
        else
            if check_eth0_up; then
                echo "NO-CARRIER is not present on eth0 and is UP. Proceeding."
                break
            else
                echo "eth0 is DOWN"
                set_eth0_up
            fi
        fi
        echo "Waiting for NO-CARRIER to clear... ($no_carrier_counter)"
        sleep 1
        let "no_carrier_counter+=1"
    done

    if [ $no_carrier_counter -ge $no_carrier_timeout ]; then
        echo "Timeout reached. NO-CARRIER is still present on eth0."    
    fi

    return 0
}

stop() {
	echo "Nothing to do, $DAEMON is not a daemon."
}

restart() {
	stop
	sleep 1
	start
}

reload() {
	echo "Nothing to do, $DAEMON does not support reload."
}

case "$1" in
	start|stop|restart|reload)
		"$1";;
	*)
		echo "Usage: $0 {start|stop|restart|reload}"
		exit 1
esac
