#!/bin/bash
#
# Checks that an internet connection exists.
# Return value is 0 on success, or another number on failure (see also: 'curl-exit-code-to-string').
#
# Example usage:
#    eos-connection-checker && echo connection is ON
#    eos-connection-checker || echo connection is OFF
#    eos-connection-checker || curl-exit-code-to-string $?

# FastestMirror assumes the list was created with eos-rankmirrors.
# Both functions below return the URLs in format: https://mirror.moson.org/endeavouros/repo/state
FastestMirror() { grep -m1 "^# https://" $ml | sed 's|# \([^$]*\)/\$.*|\1/state|' ; }
AllMirrors()    { grep "^Server[ ]*=[ ]*https://" $ml | sed 's|^Server[ ]*=[ ]*\([^$]*\)/\$.*|\1/state|' ; }

Test() {
    local url="$1"
    /usr/bin/curl --silent --fail --connect-timeout 8 "$url" >/dev/null  # download the 'state' file from a mirror
    retval=$?
    if [ $retval -eq 0 ] ; then
        [ "$verbose" = "yes" ] && echo "Mirror = $url" >&2
        exit 0                     # connection exists
    fi
}

Main() {
    local -r ml=/etc/pacman.d/endeavouros-mirrorlist
    local fastest=""
    local others=""
    local URL
    local retval=201
    local verbose=no
    local fallback="https://forum.endeavouros.com/faq"  # fallback if no mirrors in $ml

    case "$1" in
        -v | --verbose) verbose=yes ;;   # will show the responding mirror URL
    esac

    if [ -e $ml ] ; then
        fastest="$(FastestMirror)"
        if [ "$fastest" ] ; then
            Test "$fastest"
            others="$(AllMirrors | grep -v "$fastest")"
        else
            others="$(AllMirrors)"
        fi
    fi

    for URL in $others $fallback ; do
        Test "$URL"
    done
    return $retval                       # no connection
}

Main "$@"
