#!/bin/bash
# Gnosis launcher: first run creates a private Python environment, then starts
# the local server (127.0.0.1 only) and opens it in your browser.
APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$APP_DIR/Resources/gnosis"
DATA="$HOME/Library/Application Support/Gnosis"
VENV="$DATA/venv"
LOG="$HOME/Library/Logs/Gnosis.log"
PORT=5177
mkdir -p "$DATA" "$HOME/Library/Logs"
notify() { osascript -e "display notification \"$1\" with title \"Gnosis\"" >/dev/null 2>&1; }
alert()  { osascript -e "display dialog \"$1\" with title \"Gnosis\" buttons {\"OK\"} default button 1 with icon caution" >/dev/null 2>&1; }

# Already running? just open it.
if curl -s -m 1 "http://127.0.0.1:$PORT/" 2>/dev/null | grep -q 'gnosis-token'; then
  open "http://127.0.0.1:$PORT"; exit 0
fi

PY=""
for c in /opt/homebrew/bin/python3 /usr/local/bin/python3 /Library/Frameworks/Python.framework/Versions/Current/bin/python3 /usr/bin/python3; do
  [ -x "$c" ] && "$c" -c 'import sys; sys.exit(0 if sys.version_info>=(3,9) else 1)' 2>/dev/null && PY="$c" && break
done
if [ -z "$PY" ]; then
  alert "Gnosis needs Python 3.9 or newer. Install it from python.org/downloads, then open Gnosis again."
  open "https://www.python.org/downloads/"; exit 1
fi

if [ ! -x "$VENV/bin/python" ]; then
  notify "Setting up Gnosis for the first time — this takes about a minute."
  "$PY" -m venv "$VENV" >> "$LOG" 2>&1 || { alert "Couldn't create Gnosis's environment. See ~/Library/Logs/Gnosis.log"; exit 1; }
fi
STAMP="$VENV/.requirements.sha"; HASH="$(shasum "$SRC/requirements.txt" | cut -d' ' -f1)"
if [ "$(cat "$STAMP" 2>/dev/null)" != "$HASH" ]; then
  notify "Installing Gnosis components…"
  "$VENV/bin/python" -m pip install --upgrade pip >> "$LOG" 2>&1
  "$VENV/bin/python" -m pip install -r "$SRC/requirements.txt" >> "$LOG" 2>&1 \
    || { alert "Installing components failed (is the internet connected?). See ~/Library/Logs/Gnosis.log"; exit 1; }
  echo "$HASH" > "$STAMP"
fi
cd "$SRC" && nohup "$VENV/bin/python" run.py --port "$PORT" >> "$LOG" 2>&1 &
disown
exit 0
