#!/bin/zsh
# The app folder is three levels up from this binary (Tukodinge.app/Contents/MacOS/Tukodinge).
HERE="${0:A:h}"
APP="${HERE:h:h:h}"
cd "$APP" || exit 1
PORT="${TUKODINGE_PORT:-5200}"
mkdir -p data
if ! command -v python3 >/dev/null 2>&1; then
  osascript -e 'display dialog "Tukodinge needs Python. A box may appear to install Apple developer tools. Click Install, wait, then open Tukodinge again." buttons {"OK"} default button 1 with icon note'
  xcode-select --install 2>/dev/null
  exit 1
fi
[ -f data/.ready ] || { python3 setup.py >/dev/null 2>&1; touch data/.ready; }
running() { lsof -ti tcp:$PORT -sTCP:LISTEN >/dev/null 2>&1; }
if ! running; then
  nohup python3 server.py > data/server.log 2>&1 &
  for i in $(seq 1 15); do running && break; sleep 0.3; done
fi
if running; then
  open "http://localhost:$PORT"
else
  osascript -e 'display dialog "Tukodinge could not start. See data/server.log in the Tukodinge folder." buttons {"OK"} default button 1 with icon stop'
fi
