#!/bin/bash
# Purge by CrateGap: double-click launcher.
# Finds Node, starts the bundled server, opens the browser, exits.
# The server keeps running until you hit Quit inside Purge.

RESOURCES="$(cd "$(dirname "$0")/../Resources" && pwd)"
APP_DIR="$RESOURCES/purge"
DATA_DIR="$HOME/Library/Application Support/CrateGap Purge"
LOG_FILE="$HOME/Library/Logs/CrateGapPurge.log"
PORT=3000
URL="http://localhost:$PORT"

dialog() {
    /usr/bin/osascript -e "display dialog \"$1\" with title \"Purge by CrateGap\" buttons {\"$2\"} default button 1 with icon caution" >/dev/null 2>&1
}

# GUI apps get a bare PATH; include the places Node actually lives.
export PATH="/opt/homebrew/bin:/usr/local/bin:/opt/local/bin:$PATH"

NODE_BIN="$(command -v node || true)"
if [ -z "$NODE_BIN" ]; then
    /usr/bin/osascript -e 'display dialog "Purge needs Node.js (free, one-time install).\n\nClick Get Node.js, install the LTS version, then open Purge again." with title "Purge by CrateGap" buttons {"Cancel", "Get Node.js"} default button 2 with icon caution' >/dev/null 2>&1 \
        && /usr/bin/open "https://nodejs.org"
    exit 0
fi

# Already running? Just bring up the browser.
if /usr/bin/curl -s -o /dev/null --max-time 1 "$URL/api/playlists"; then
    /usr/bin/open "$URL"
    exit 0
fi

mkdir -p "$DATA_DIR" "$(dirname "$LOG_FILE")"

cd "$APP_DIR" || { dialog "Purge could not find its own files. Re-download from crategap.com/purge." "OK"; exit 1; }

PURGE_DATA_DIR="$DATA_DIR" PORT="$PORT" /usr/bin/nohup "$NODE_BIN" server.js >> "$LOG_FILE" 2>&1 &
SERVER_PID=$!

# Wait up to 10s for the server to come up.
for _ in $(seq 1 40); do
    if /usr/bin/curl -s -o /dev/null --max-time 1 "$URL/api/playlists"; then
        /usr/bin/open "$URL"
        exit 0
    fi
    if ! kill -0 "$SERVER_PID" 2>/dev/null; then
        dialog "Purge failed to start. Details are in ~/Library/Logs/CrateGapPurge.log" "OK"
        exit 1
    fi
    sleep 0.25
done

dialog "Purge is taking too long to start. Details are in ~/Library/Logs/CrateGapPurge.log" "OK"
exit 1
