#!/bin/sh

filesettings="/etc/enigma2/settings"
checkconfig="config.wireguard.timeoutyesno=False"

modprobe wireguard
[ -e /dev/fd ] || ln -sf /proc/self/fd /dev/fd

check_internet_connection() {
    local timeout=1
    local max_attempts=10

    for _ in $(seq "$max_attempts"); do
        if ping -q -c 1 -W "$timeout" 8.8.8.8 >/dev/null; then
            return 0  # Success
        fi
        sleep 1
    done

    return 1  # Failure after max_attempts
}

case "$1" in
    start)
        if grep -q "$checkconfig" "$filesettings"; then
          echo "Starting Wireguard interface: wg0"
          wg-quick up wg0
        else
          if check_internet_connection; then
            echo "Internet connection OK"
            echo "Starting Wireguard interface: wg0"
            wg-quick up wg0
          else
            echo "No internet connection"
            wg-quick down wg0
            exit 0
          fi
        fi
        ;;

    stop)
        echo "Stopping Wireguard interface: wg0"
        wg-quick down wg0
        ;;

    restart)
        wg-quick stop wg0
        sleep 1
        echo "Starting Wireguard interface: wg0"
        wg-quick start wg0
        ;;

    status)
        wg show wg0
        ;;

    *)
        echo "(start|stop|restart|status)"
        ;;
esac

exit 0 &
