#!/usr/bin/env bash

export PORT=${PORT:-3000}
USE_TAILSCALE=0
RAILS_ARGS=()

for arg in "$@"; do
  case $arg in
    --tailscale) USE_TAILSCALE=1 ;;
    --help|-h)
      cat <<USAGE
Usage: bin/dev [options] [rails server options]

Starts the Campfire development server on \$PORT (default 3000).

Options:
  --tailscale   Expose the dev server via tailscale serve
  -h, --help    Show this help
USAGE
      exit 0
      ;;
    *) RAILS_ARGS+=("$arg") ;;
  esac
done

if [ "$USE_TAILSCALE" = "1" ]; then
  if ! command -v tailscale >/dev/null 2>&1; then
    echo "Error: tailscale not found" >&2
    exit 1
  fi

  if ! TS_STATUS=$(tailscale status --self --json 2>/dev/null); then
    echo "Error: tailscale not logged in" >&2
    exit 1
  fi

  TS_HOSTNAME=$(echo "$TS_STATUS" | jq -r '.Self.DNSName | rtrimstr(".")')
  TS_PORT="4$PORT"

  stop_tailscale() { tailscale serve --https=$TS_PORT off >/dev/null 2>&1; }
  trap stop_tailscale EXIT INT TERM

  tailscale serve --bg --https=$TS_PORT localhost:$PORT >/dev/null 2>&1
  if ! tailscale serve status --json 2>/dev/null | jq -e ".TCP.\"$TS_PORT\"" >/dev/null 2>&1; then
    echo "Error: tailscale serve failed. On Linux, run once: sudo tailscale set --operator=\$USER" >&2
    exit 1
  fi

  echo "Serving on https://$TS_HOSTNAME:$TS_PORT/"
  ./bin/rails server "${RAILS_ARGS[@]}"
else
  exec ./bin/rails server "${RAILS_ARGS[@]}"
fi
