#!/usr/bin/env bash
# check-port.sh — list free ports in the 3010-3020 range commonly used for ad-hoc previews.
# Exits 0 on success. Prints "FREE" / "TAKEN" per port.
#
# Usage: check-port.sh                    # checks 3010-3020
#        check-port.sh 3000 3010 8080     # checks specific ports
#        check-port.sh --json 3010 3011   # machine-readable

set -euo pipefail

JSON=0
PORTS=()
for arg in "$@"; do
  if [[ "$arg" == "--json" ]]; then
    JSON=1
  else
    PORTS+=("$arg")
  fi
done

if [[ ${#PORTS[@]} -eq 0 ]]; then
  PORTS=(3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020)
fi

# ss -tlnp requires no root for the listen-port listing, but the PID/program columns are
# blank without privileges. We only need the port column, so this works as the ubuntu user.
LISTENED=$(ss -tlnH 2>/dev/null | awk '{print $4}' | grep -oE ':[0-9]+$' | tr -d ':' | sort -un || true)

if [[ $JSON -eq 1 ]]; then
  echo "["
  first=1
  for p in "${PORTS[@]}"; do
    if grep -qx "$p" <<< "$LISTENED"; then state="TAKEN"; else state="FREE"; fi
    [[ $first -eq 0 ]] && echo ","
    first=0
    printf '  {"port": %s, "state": "%s"}' "$p" "$state"
  done
  echo
  echo "]"
else
  for p in "${PORTS[@]}"; do
    if grep -qx "$p" <<< "$LISTENED"; then
      echo "$p TAKEN"
    else
      echo "$p FREE"
    fi
  done
fi
