#!/bin/bash
# VeraDrive launcher: starts the local server in the background and opens it in your browser.
APP_DIR="$(cd "$(dirname "$0")/../Resources/app" && pwd)"
STATE="$HOME/.veradrive"
URL_FILE="$STATE/server_url"
LOG="$STATE/veradrive.log"
mkdir -p "$STATE"

healthy() {
  [ -f "$URL_FILE" ] || return 1
  URL="$(cat "$URL_FILE")"
  /usr/bin/curl -s -m 2 "$URL/" | /usr/bin/grep -q "VeraDrive"
}

open_page() {
  [ -n "$VERADRIVE_NO_OPEN" ] || /usr/bin/open "$URL"
}

if healthy; then
  open_page
  exit 0
fi
rm -f "$URL_FILE"

PYTHON=""
for candidate in \
  /Library/Frameworks/Python.framework/Versions/Current/bin/python3 \
  /opt/homebrew/bin/python3 \
  /usr/local/bin/python3 \
  /usr/bin/python3; do
  [ -x "$candidate" ] || continue
  if [ "$candidate" = "/usr/bin/python3" ] && ! /usr/bin/xcode-select -p >/dev/null 2>&1; then continue; fi
  if "$candidate" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 9) else 1)' >/dev/null 2>&1; then
    PYTHON="$candidate"
    break
  fi
done

if [ -z "$PYTHON" ]; then
  CHOICE="$(/usr/bin/osascript -e 'button returned of (display dialog "VeraDrive needs Python 3.9 or newer.\n\nInstall it from python.org, then open VeraDrive again." buttons {"Cancel", "Open python.org"} default button 2 with icon caution with title "VeraDrive")' 2>/dev/null)"
  [ "$CHOICE" = "Open python.org" ] && /usr/bin/open "https://www.python.org/downloads/macos/"
  exit 1
fi

cd "$APP_DIR" || exit 1
nohup "$PYTHON" -u run_veradrive.py --no-browser >> "$LOG" 2>&1 &

for _ in $(seq 1 60); do
  if healthy; then
    open_page
    exit 0
  fi
  sleep 0.5
done

/usr/bin/osascript -e 'display dialog "VeraDrive could not start.\n\nDetails are in ~/.veradrive/veradrive.log" buttons {"OK"} default button 1 with icon stop with title "VeraDrive"' >/dev/null 2>&1
exit 1
