#!/bin/env fish
function waitNetwork -a witness
    set -l timeout (math 10 \* 60)
    set -l codeFile (mktemp)

    function testNetwork
        # Ping digitalcourage DNS server
        # https://digitalcourage.de/
        ping -q -c1 5.9.164.112 >/dev/null
    end

    if [ -z "$witness" ]
        if not testNetwork &>/dev/null
            tmux new-session -s network -d 'cat /etc/motd; echo "$(tput bold)Please establish an internet connection...$(tput sgr0)"; $SHELL'
            fish (status filename) true &
            set -l pid "$last_pid"

            function witnessHandler -V codeFile --on-process-exit "$pid" -a event pid code
                echo "$code" >"$codeFile"

                if [ "$code" -gt 0 ]
                    echo "Unable to connect to the internet!"
                end
            end

            TMUX="" tmux attach -t network
            wait "$pid"
            return "$(cat "$codeFile")"
        end
    else
        set -l x 0

        while true
            set x (math $x + 1)

            if testNetwork &>/dev/null
                tmux kill-session -t network &>/dev/null
                break
            else
                not tmux list-sessions -f "#{==:#S,network}" &>/dev/null
                or test "$x" -gt 120
                and begin
                    tmux kill-session -t network &>/dev/null
                    exit 1
                end
            end

            sleep 1
        end
    end
end

if [ -n "$argv" ]
    waitNetwork $argv
end