#!/usr/bin/env bash
set -Eeuo pipefail

SCRIPT_NAME="$(basename "$0")"
STRICT=0
IFACE=""

usage() {
    cat <<'EOF'
Usage: vpn-check.sh [options]

Read-only VPN status checks for lab networks.

Options:
  --interface IFACE  Check a specific interface instead of tun*/wg*.
  --strict           Exit non-zero when no VPN interface is detected.
  -h, --help         Show this help.
EOF
}

while (( $# > 0 )); do
    case "$1" in
        --interface)
            (( $# >= 2 )) || { echo "--interface requires a value." >&2; exit 2; }
            IFACE="$2"
            shift
            ;;
        --strict) STRICT=1 ;;
        -h|--help)
            usage
            exit 0
            ;;
        *) echo "Unknown option: $1" >&2; exit 2 ;;
    esac
    shift
done

section() {
    printf '\n== %s ==\n' "$1"
}

section Interfaces
if ! command -v ip >/dev/null 2>&1; then
    printf '[%s] ip command unavailable; interface and route checks were skipped.\n' "$SCRIPT_NAME"
    found=0
elif [[ -n "$IFACE" ]]; then
    if ip link show "$IFACE" >/dev/null 2>&1; then
        ip -brief address show "$IFACE"
        found=1
    else
        printf '[%s] Interface not found: %s\n' "$SCRIPT_NAME" "$IFACE"
        found=0
    fi
else
    matches="$(ip -brief address show 2>/dev/null | awk '$1 ~ /^(tun|wg)/ { print }')"
    if [[ -n "$matches" ]]; then
        printf '%s\n' "$matches"
        found=1
    else
        printf '[%s] No tun*/wg* interface detected.\n' "$SCRIPT_NAME"
        found=0
    fi
fi

section Routes
if command -v ip >/dev/null 2>&1; then
    ip route show
else
    printf 'ip command unavailable\n'
fi

section DNS
if [[ -r /etc/resolv.conf ]]; then
    awk '/^nameserver/ { print }' /etc/resolv.conf
else
    printf 'Cannot read /etc/resolv.conf\n'
fi

section "External IP"
if command -v curl >/dev/null 2>&1; then
    curl -fsS --max-time 5 https://ifconfig.me 2>/dev/null || printf 'External IP lookup failed'
    printf '\n'
elif command -v wget >/dev/null 2>&1; then
    wget -qO- --timeout=5 https://ifconfig.me 2>/dev/null || printf 'External IP lookup failed'
    printf '\n'
else
    printf 'curl or wget unavailable\n'
fi

if (( STRICT == 1 && found == 0 )); then
    exit 1
fi
