#!/usr/bin/env bash

set -u
set -o pipefail

NETBIRD_TEST_HOST=""
REPORT_FILE="${REPORT_FILE:-}"
RUN_ONESHOT=0

PING_COUNT="${PING_COUNT:-3}"
PING_TIMEOUT="${PING_TIMEOUT:-3}"

FAILED=0
WARNINGS=0
SKIPPED=0
TOTAL=0

if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then
  GREEN="\033[0;32m"
  RED="\033[0;31m"
  YELLOW="\033[0;33m"
  BLUE="\033[0;34m"
  BOLD="\033[1m"
  RESET="\033[0m"
else
  GREEN=""
  RED=""
  YELLOW=""
  BLUE=""
  BOLD=""
  RESET=""
fi

usage() {
  cat <<EOF
Usage:
  $0 [options] [netbird-test-host-or-ip]

Options:
  -o, --output FILE     Write a plain-text report to FILE
  --run-oneshot         Actively run go-ws-restart before checking result
  -h, --help            Show this help

Examples:
  $0 100.64.12.34
  $0 --output /tmp/kiosk-test-report.txt 100.64.12.34
  $0 --run-oneshot --output /tmp/kiosk-test-report.txt 100.64.12.34

Environment variables:
  NETBIRD_TEST_HOST     NetBird peer IP/hostname to ping
  REPORT_FILE           Output report path
  PING_COUNT            Ping count, default: 3
  PING_TIMEOUT          Ping timeout seconds, default: 3
  NO_COLOR              Disable colored terminal output
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    -o|--output)
      REPORT_FILE="${2:-}"
      shift 2
      ;;
    --run-oneshot)
      RUN_ONESHOT=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      NETBIRD_TEST_HOST="$1"
      shift
      ;;
  esac
done

NETBIRD_TEST_HOST="${NETBIRD_TEST_HOST:-${NETBIRD_TEST_HOST:-}}"

if [[ -n "$REPORT_FILE" ]]; then
  mkdir -p -- "$(dirname -- "$REPORT_FILE")"
  : > "$REPORT_FILE" || {
    echo "ERROR: Could not write to report file: $REPORT_FILE" >&2
    exit 2
  }
fi

log_plain() {
  if [[ -n "$REPORT_FILE" ]]; then
    printf "%s\n" "$1" >> "$REPORT_FILE"
  fi
}

say() {
  local terminal_text="$1"
  local plain_text="${2:-$1}"

  printf "%b\n" "$terminal_text"
  log_plain "$plain_text"
}

print_header() {
  local hostname_now
  local date_now

  hostname_now="$(hostname -f 2>/dev/null || hostname)"
  date_now="$(date '+%Y-%m-%d %H:%M:%S %Z')"

  say ""
  say "${BOLD}${BLUE}System Test Results${RESET}" "System Test Results"
  say "==================================================" "=================================================="
  say "Host: $hostname_now"
  say "Date: $date_now"
  say "User: $(whoami)"
  say ""
}

print_result() {
  local status="$1"
  local name="$2"
  local details="$3"
  local color=""

  TOTAL=$((TOTAL + 1))

  case "$status" in
    PASS)
      color="$GREEN"
      ;;
    FAIL)
      color="$RED"
      FAILED=$((FAILED + 1))
      ;;
    WARN)
      color="$YELLOW"
      WARNINGS=$((WARNINGS + 1))
      ;;
    SKIP)
      color="$YELLOW"
      SKIPPED=$((SKIPPED + 1))
      ;;
  esac

  printf "%b[%-4s]%b %-34s %s\n" "$color" "$status" "$RESET" "$name" "$details"

  if [[ -n "$REPORT_FILE" ]]; then
    printf "[%-4s] %-34s %s\n" "$status" "$name" "$details" >> "$REPORT_FILE"
  fi
}

indent_output() {
  sed 's/^/       /'
}

systemctl_value() {
  local unit="$1"
  local property="$2"

  systemctl show "$unit" --property="$property" --value 2>/dev/null || true
}

check_command() {
  local cmd="$1"

  if command -v "$cmd" >/dev/null 2>&1; then
    print_result "PASS" "Command: $cmd" "found at $(command -v "$cmd")"
    return 0
  else
    print_result "FAIL" "Command: $cmd" "not found"
    return 1
  fi
}

check_service_running() {
  local service="$1"

  if ! command -v systemctl >/dev/null 2>&1; then
    print_result "FAIL" "Service: $service" "systemctl is not available"
    return 1
  fi

  if systemctl is-active --quiet "$service"; then
    print_result "PASS" "Service: $service" "running"
    return 0
  else
    local state
    state="$(systemctl is-active "$service" 2>/dev/null || true)"
    print_result "FAIL" "Service: $service" "not running, state: ${state:-unknown}"
    return 1
  fi
}

check_oneshot_service() {
  local service="$1"

  if ! command -v systemctl >/dev/null 2>&1; then
    print_result "FAIL" "Oneshot: $service" "systemctl is not available"
    return 1
  fi

  local load_state
  local unit_type
  local active_state
  local sub_state
  local result
  local exec_status
  local exit_timestamp
  local enabled_state

  load_state="$(systemctl_value "$service" "LoadState")"
  unit_type="$(systemctl_value "$service" "Type")"
  active_state="$(systemctl_value "$service" "ActiveState")"
  sub_state="$(systemctl_value "$service" "SubState")"
  result="$(systemctl_value "$service" "Result")"
  exec_status="$(systemctl_value "$service" "ExecMainStatus")"
  exit_timestamp="$(systemctl_value "$service" "ExecMainExitTimestamp")"
  enabled_state="$(systemctl is-enabled "$service" 2>/dev/null || true)"

  if [[ "$load_state" != "loaded" ]]; then
    print_result "FAIL" "Oneshot: $service" "unit is not loaded, LoadState=${load_state:-unknown}"
    return 1
  fi

  if [[ "$unit_type" != "oneshot" ]]; then
    print_result "WARN" "Oneshot: $service" "unit Type is ${unit_type:-unknown}, expected oneshot"
  fi

  if [[ "$RUN_ONESHOT" -eq 1 ]]; then
    if systemctl start "$service" >/tmp/oneshot-test.out 2>&1; then
      print_result "PASS" "Oneshot run: $service" "started successfully"
    else
      print_result "FAIL" "Oneshot run: $service" "systemctl start failed"
      indent_output < /tmp/oneshot-test.out
      if [[ -n "$REPORT_FILE" ]]; then
        indent_output < /tmp/oneshot-test.out >> "$REPORT_FILE"
      fi
      return 1
    fi

    result="$(systemctl_value "$service" "Result")"
    exec_status="$(systemctl_value "$service" "ExecMainStatus")"
    active_state="$(systemctl_value "$service" "ActiveState")"
    sub_state="$(systemctl_value "$service" "SubState")"
    exit_timestamp="$(systemctl_value "$service" "ExecMainExitTimestamp")"
  fi

  if [[ "$enabled_state" == "enabled" ]]; then
    print_result "PASS" "Oneshot enabled: $service" "enabled"
  else
    print_result "WARN" "Oneshot enabled: $service" "state: ${enabled_state:-unknown}"
  fi

  if [[ "$result" == "success" && "$exec_status" == "0" ]]; then
    print_result "PASS" "Oneshot result: $service" "last result successful; ActiveState=$active_state/$sub_state"
    if [[ -n "$exit_timestamp" ]]; then
      say "       Last exit: $exit_timestamp"
    fi
    return 0
  fi

  if [[ "$result" == "success" && -z "$exec_status" ]]; then
    print_result "WARN" "Oneshot result: $service" "result is success, but ExecMainStatus is empty"
    return 0
  fi

  print_result "FAIL" "Oneshot result: $service" "Result=${result:-unknown}, ExecMainStatus=${exec_status:-unknown}, ActiveState=$active_state/$sub_state"
  return 1
}

check_netbird_status() {
  if ! command -v netbird >/dev/null 2>&1; then
    print_result "FAIL" "NetBird status" "netbird command not found"
    return 1
  fi

  local output
  if ! output="$(netbird status 2>&1)"; then
    print_result "FAIL" "NetBird status" "netbird status command failed"
    echo "$output" | indent_output
    if [[ -n "$REPORT_FILE" ]]; then
      echo "$output" | indent_output >> "$REPORT_FILE"
    fi
    return 1
  fi

  if echo "$output" | grep -qi "connected"; then
    print_result "PASS" "NetBird status" "reports connected"
    return 0
  else
    print_result "WARN" "NetBird status" "status did not clearly report connected"
    echo "$output" | indent_output
    if [[ -n "$REPORT_FILE" ]]; then
      echo "$output" | indent_output >> "$REPORT_FILE"
    fi
    return 0
  fi
}

check_netbird_traffic() {
  if [[ -z "$NETBIRD_TEST_HOST" ]]; then
    print_result "SKIP" "NetBird traffic" "no test host provided"
    return 0
  fi

  if ! command -v ping >/dev/null 2>&1; then
    print_result "FAIL" "NetBird traffic" "ping command not found"
    return 1
  fi

  local ping_output
  ping_output="$(mktemp)"

  if ping -c "$PING_COUNT" -W "$PING_TIMEOUT" "$NETBIRD_TEST_HOST" >"$ping_output" 2>&1; then
    print_result "PASS" "NetBird traffic" "ping succeeded to $NETBIRD_TEST_HOST"
    tail -n 2 "$ping_output" | indent_output
    if [[ -n "$REPORT_FILE" ]]; then
      tail -n 2 "$ping_output" | indent_output >> "$REPORT_FILE"
    fi
    rm -f "$ping_output"
    return 0
  else
    print_result "FAIL" "NetBird traffic" "could not ping $NETBIRD_TEST_HOST"
    indent_output < "$ping_output"
    if [[ -n "$REPORT_FILE" ]]; then
      indent_output < "$ping_output" >> "$REPORT_FILE"
    fi
    rm -f "$ping_output"
    return 1
  fi
}

print_summary() {
  say ""
  say "==================================================" "=================================================="

  if [[ "$FAILED" -eq 0 ]]; then
    if [[ "$WARNINGS" -eq 0 ]]; then
      say "${GREEN}${BOLD}All required tests passed.${RESET}" "All required tests passed."
    else
      say "${YELLOW}${BOLD}Required tests passed, but there were warnings.${RESET}" "Required tests passed, but there were warnings."
    fi
  else
    say "${RED}${BOLD}$FAILED required test(s) failed.${RESET}" "$FAILED required test(s) failed."
  fi

  say "Total checks: $TOTAL"
  say "Failures:     $FAILED"
  say "Warnings:     $WARNINGS"
  say "Skipped:      $SKIPPED"

  if [[ -n "$REPORT_FILE" ]]; then
    say ""
    say "Report written to: $REPORT_FILE"
  fi

  say ""
}

main() {
  print_header

  check_command "systemctl"
  check_command "netbird"

  say ""
  check_service_running "go-ws"
  check_oneshot_service "go-ws-restart"
  check_service_running "netbird"

  say ""
  check_netbird_status
  check_netbird_traffic

  print_summary

  if [[ "$FAILED" -eq 0 ]]; then
    exit 0
  else
    exit 1
  fi
}

main