#!/bin/sh -e
#
# isitup - check [domain.tld] for uptime

# check if $1 is reachable on port $2
# 1) curl-tor "https://isitup.org/$1.json" | jq ;;

case "$#" in
  1)
    url="$1"
    start="$(date +%s)"
    printf "Checking your connection...\r"
    while ! ping -c1 -W2 "${url}" 1>/dev/null 2>/dev/null; do
      end="$(date +%s)"
      timedifference="$((end - start))"
      tdm="$((timedifference / 60))"
      tds="$((timedifference % 60))"
      printf "\x1b[2K"
      # shellcheck disable=SC2250
      printf "You have been down for %sm%ss\r" "$tdm" "$tds"
      sleep 1
    done
    end="$(date +%s)"
    echo "You are now connected. You were down for $((end - start)) seconds."
    ;;
  2)
    domain="$1"
    port="$2"
    nc -zw1 "${1}" "${2}"
    ret="$?"
    if [ "${ret}" -ne 0 ]; then
      printf "Connection to %s port %s failed!\n" "${domain}" "${port}"
      exit 1
    fi
    exit 0
    ;;
  *)
    printf '%s\n' "Usage: $(basename "$0") [domain.tld/IP] <port>"
    exit 1
    ;;
esac
