#!/bin/bash
# Port Security launcher: asks for administrator rights, starts the local service as root,
# then opens the window in your browser (Chrome/Edge/Brave app-mode if installed).
APP="$(cd "$(dirname "$0")/../Resources/app" && pwd)"

DOTNET=""
for c in /usr/local/share/dotnet/dotnet /opt/homebrew/bin/dotnet /usr/local/bin/dotnet "$HOME/.dotnet/dotnet" "$(command -v dotnet)"; do
  [ -x "$c" ] && { DOTNET="$c"; break; }
done
if [ -z "$DOTNET" ]; then
  osascript -e 'display dialog "Port Security needs the .NET 8 runtime.\n\nInstall it from https://dotnet.microsoft.com/download/dotnet/8.0 (choose the macOS .NET Runtime for your Mac), then open Port Security again." buttons {"OK"} default button "OK" with icon caution'
  open "https://dotnet.microsoft.com/download/dotnet/8.0"
  exit 1
fi
DOTNET_ROOT_DIR="$(dirname "$(readlink "$DOTNET" 2>/dev/null || echo "$DOTNET")")"
case "$DOTNET_ROOT_DIR" in /*) ;; *) DOTNET_ROOT_DIR="$(dirname "$DOTNET")";; esac

PORT=$((20000 + RANDOM % 20000))
TF="$(mktemp /tmp/portsecurity.XXXXXX)"; chmod 600 "$TF"
TOKEN="$(uuidgen | tr -d '-')"; echo "$TOKEN" > "$TF"

osascript -e "do shell script \"DOTNET_ROOT='$DOTNET_ROOT_DIR' '$DOTNET' '$APP/portsecurity.dll' --port $PORT --token-file '$TF' --no-open >/dev/null 2>&1 &\" with administrator privileges" >/dev/null 2>&1 \
  || { rm -f "$TF"; exit 1; }

URL="http://127.0.0.1:$PORT/?t=$TOKEN"
for i in $(seq 1 60); do
  curl -s -o /dev/null --max-time 1 "$URL" && break
  sleep 0.25
done

for b in "Google Chrome" "Microsoft Edge" "Brave Browser"; do
  if [ -d "/Applications/$b.app" ]; then open -na "$b" --args --app="$URL" --window-size=1000,720 && exit 0; fi
done
open "$URL"
