#!/usr/bin/env sh
# Connectivity check for Get K3S - run from inside the restricted network.
# Generated by pullist on 2026-09-22. Needs: curl.
# Any HTTP status counts as reachable; we only test that TCP/TLS gets through.
usage() {
  cat <<EOF
Usage: ${0##*/} [OPTIONS]

Check HTTP/HTTPS connectivity to configured hosts.

Options:
  --color       Enable colored output
  --no-color    Disable colored output
  -h, --help    Show this help

Color is enabled automatically when output is connected to a terminal.
EOF
}

color=auto

while [ "$#" -gt 0 ]; do
  case "$1" in
    --color)
      color=true
      ;;
    --no-color)
      color=false
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      printf 'Unknown option: %s\n\n\' "$1" >&2
      usage >&2
      exit 2
      ;;
  esac
  shift
done

if [ "$color" = auto ]; then
  [ -t 1 ] && color=true || color=false
fi

if "$color"; then
  green=$'[32m'
  red=$'[31m'
  reset=$'[0m'
else
  green=""
  red=""
  reset=""
fi

# Fail fast if curl is not available
if ! command -v curl >/dev/null 2>&1; then
  printf "%sFAIL%s  curl is not installed or not in PATH
" \
    "$red" "$reset"
  exit 127
fi

fail=0

curl_error() {
  case "$1" in
    1)  printf "%s" "unsupported protocol" ;;
    3)  printf "%s" "url malformat" ;;
    5)  printf "%s" "could not resolve proxy" ;;
    6)  printf "%s" "could not resolve host" ;;
    7)  printf "%s" "failed to connect to host" ;;
    8)  printf "%s" "wierd server reply" ;;
    16) printf "%s" "detected problem in the HTTP framing layer" ;;
    22) printf "%s" "HTTP error (400 or greater)" ;;
    28) printf "%s" "operation timed out" ;;
    35) printf "%s" "TLS/SSL connection error" ;;
    47) printf "%s" "too many redirects" ;;
    52) printf "%s" "server returned no data" ;;
    55) printf "%s" "failed sending network data" ;;
    56) printf "%s" "failed receiving network data" ;;
    58) printf "%s" "problem with local client certificate" ;;
    60) printf "%s" "server certificate could not be authenticated" ;;
    77) printf "%s" "problem reading CA certificate" ;;
    92) printf "%s" "HTTP/2 stream error" ;;
    95) printf "%s" "HTTP/3 error" ;;
    96) printf "%s" "QUIC connection error" ;;
    97) printf "%s" "proxy handshake error" ;;
    98) printf "%s" "client certificate required" ;;
    *)  printf "%s" "curl error" ;;
  esac
}

check() {
  code=$(curl -sS -o /dev/null -w "%{http_code}" \
    --connect-timeout 5 "$1" 2>/dev/null)
  rc=$?

  if [ "$rc" -eq 0 ] || [ "$code" != "000" ]; then
    printf "%sOK%s    %s
" "$green" "$reset" "$1"
  else
    printf "%sFAIL%s  %s  (curl exit %s: %s)
" \
      "$red" "$reset" "$1" "$rc" "$(curl_error "$rc")"
    fail=1
  fi
}
check https://get.k3s.io/
check https://github.com/
check https://update.k3s.io/
check https://api.github.com/
check https://rpm.rancher.io/
exit $fail
