#!/bin/bash
# Desc:Marks the time when a remote server can be pinged.
# Depends: GNU Coreutils 8.32 (date, sleep), iputils-ping 3:20211215-1 (ping)
# Version: 0.1.0

delay=10;
domain="google.com"

yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails

if [[ -n "$1" ]]; then domain="$1"; fi;

SECONDS=0;
printf "%s:STATUS:Starting ping...\n" "$(date -Is)";
while [[ ! noPing == "true" ]]; do
    printf "%s:" "$(date -Is)"; # prepend line with date
    ping -c1 "$domain"; pingExitCode="$?"; # perform ping
    
    if [[ "$pingExitCode" -eq 0 ]]; then
        # Case if ping succeeded
        printf "%s:Ping resolved after $SECONDS seconds.\n" "$(date -Is)";
        exit 0;
    elif [[ "$pingExitCode" -eq 1 ]]; then
        sleep "$delay";
        continue;
    else
        die "FATAL:Unknown error.";
        exit 1;
    fi;
done;

yell "ERROR:Here be dragons.";
exit 1;
