#!/bin/bash

CONF="/etc/netwatch.conf"
CP_CONF="/etc/captive-portal.conf"

test -s ${CONF} || exit 0
source ${CONF}
source ${CP_CONF}

test -n "${OS_VERSION}" || source /etc/init.d/base

test "${OS_NETWORKLESS}" == "true" && exit 0


function gw_ok() {
    def_route=$(ip route | grep default | head -n 1)
    test -n "${def_route}" || return 1  # no default route
    
    grep -q via <<< ${def_route} || return 0  # default route w/o via
    
    gw=$(cut -d ' ' -f 3 <<< ${def_route})
    test -n "${gw}" || return 1  # no gateway
    
    ping -c 2 -W 2 -w 3 ${gw} &>/dev/null
}

function gw_watch() {
    count=0
    GW_WATCH_RETRIES=$((${GW_WATCH_RETRIES} - 1))
    while true; do
        sleep ${GW_WATCH_INTERVAL}
        if gw_ok 2>&1; then
            count=0
        else
            if [[ ${count} -lt ${GW_WATCH_RETRIES} ]]; then
                logger -t netwatch "gateway not reachable"
                count=$((${count} + 1))
                continue
            else
                panic action netwatch "gateway not reachable"
            fi
        fi
    done
}

function net_watch() {
    sleep ${NET_WATCH_DELAY}

    count=0
    NET_WATCH_RETRIES=$((${NET_WATCH_RETRIES} - 1))
    while true; do
        sleep ${NET_WATCH_INTERVAL}
        if nc -z -w ${NET_WATCH_TIMEOUT} ${NET_WATCH_HOST} ${NET_WATCH_PORT} </dev/null >/dev/null 2>&1; then
            count=0
        else
            if [[ ${count} -lt ${NET_WATCH_RETRIES} ]]; then
                logger -t netwatch "cannot connect to ${NET_WATCH_HOST}:${NET_WATCH_PORT}"
                count=$((${count} + 1))
                continue
            else
                panic action netwatch "cannot connect to ${NET_WATCH_HOST}:${NET_WATCH_PORT}"
            fi
        fi
    done
}

function start() {
    if [[ ${CAPTIVE_PORTAL_ENABLED} == true ]] && \
       [[ -n "${CAPTIVE_PORTAL_CONFIGURED_CMD}" ]] && \
       ! eval ${CAPTIVE_PORTAL_CONFIGURED_CMD} &>/dev/null; then
       
       exit 0
    fi

    msg_begin "Starting netwatch"
    if [[ -n "${NET_WATCH_HOST}" ]] && [[ -n "${NET_WATCH_PORT}" ]]; then
        net_watch &
    fi
    if [[ "${GW_WATCH}" == true ]]; then
        gw_watch &
    fi
    msg_done
}

function stop() {
    msg_begin "Stopping netwatch"
    ps | grep $(basename $0) | grep -v $$ | grep -v grep | tr -s ' ' | sed -e 's/^\s//' | cut -d ' ' -f 1 | xargs -r kill
    msg_done
}

case "$1" in
    start)
        start
        ;;

    stop)
        stop
        ;;

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

exit $?
