#!/bin/bash
# Kontor.app (installierte Version mit eigenem Python). Startet den Kontor-Server im Hintergrund
# und öffnet Kontor im Browser. Daten: ~/Library/Application Support/Kontor/daten
PORT="${KONTOR_PORT:-8765}"
URL="http://localhost:${PORT}/"
R="$(cd "$(dirname "$0")/../Resources" && pwd)"
EINST="$HOME/Library/Application Support/Kontor"
LOG="$EINST/kontor.log"
mkdir -p "$EINST"

meldung() {
  /usr/bin/osascript -e "display dialog \"$1\" buttons {\"OK\"} default button 1 with icon ${2:-caution} with title \"Kontor\"" >/dev/null 2>&1
}
laeuft() { /usr/bin/curl -s -m 1 -o /dev/null "${URL}api/info"; }

if laeuft; then /usr/bin/open "$URL"; exit 0; fi

case "$R" in
  */AppTranslocation/*)
    meldung "Bitte Kontor zuerst in den Ordner «Programme» ziehen und von dort öffnen." ; exit 1 ;;
esac

ARCH="$(/usr/bin/uname -m)"
PY="$R/python-$ARCH/bin/python3.12"
[ -x "$PY" ] || PY="$R/python-x86_64/bin/python3.12"
if [ ! -x "$PY" ]; then meldung "Kontor ist unvollständig (Python fehlt). Bitte neu herunterladen."; exit 1; fi

# Quarantäne-Markierung des Downloads entfernen, sonst blockiert macOS das mitgelieferte Python
/usr/bin/xattr -dr com.apple.quarantine "$R/.." 2>/dev/null

echo "=== Start $(date '+%Y-%m-%d %H:%M:%S') ($ARCH) ===" >> "$LOG"
cd "$R/kontor" || exit 1
nohup "$PY" -E -s -B server.py --kein-browser >> "$LOG" 2>&1 &

for i in $(seq 1 60); do
  if laeuft; then /usr/bin/open "$URL"; exit 0; fi
  sleep 0.25
done
meldung "Kontor konnte nicht gestartet werden.\n\nDas Protokoll steht in:\n$LOG"
exit 1
