#!/bin/sh
# JSend — macOS launcher (Contents/MacOS/JSend inside "JSend.app").
#
# Finds python3, starts the JSend PC app exactly as the Windows
# entry point does (pc/jsend_app.py, which serves the local web UI
# on 127.0.0.1 and opens it in the default browser), and keeps a log
# next to the app data (~/Downloads/JSend/JSend.log) so any
# failure can be diagnosed later. POSIX sh — no bash-isms, because
# Finder launches .app executables with a minimal environment.

# --- locate ourselves -------------------------------------------------
# $0 is .../JSend.app/Contents/MacOS/JSend
MACOS_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
CONTENTS_DIR=$(dirname -- "$MACOS_DIR")
APP_DIR="$CONTENTS_DIR/Resources/app"
ENTRY="$APP_DIR/pc/jsend_app.py"

# --- log file (next to the app data) ----------------------------------
DATA_DIR="$HOME/Downloads/JSend"
mkdir -p "$DATA_DIR" 2>/dev/null
LOG="$DATA_DIR/JSend.log"
{
    echo "---- JSend launch: $(date '+%Y-%m-%d %H:%M:%S %z')"
    echo "app: $CONTENTS_DIR"
} >> "$LOG" 2>/dev/null

say_problem() {
    # $1 = message. Dialog when we can, terminal echo otherwise.
    if command -v osascript >/dev/null 2>&1; then
        osascript -e "display dialog \"$1\" buttons {\"OK\"} default button \"OK\" with title \"JSend\"" >/dev/null 2>&1 || printf '%s\n' "$1"
    else
        printf '%s\n' "$1"
    fi
    echo "ERROR: $1" >> "$LOG" 2>/dev/null
}

# --- find python3 -------------------------------------------------------
PY=""
for cand in /usr/bin/python3 /opt/homebrew/bin/python3 /usr/local/bin/python3; do
    if [ -x "$cand" ] && "$cand" -c 'import sys' >/dev/null 2>&1; then
        PY="$cand"
        break
    fi
done
if [ -z "$PY" ]; then
    cand=$(command -v python3 2>/dev/null)
    if [ -n "$cand" ] && "$cand" -c 'import sys' >/dev/null 2>&1; then
        PY="$cand"
    fi
fi

if [ -z "$PY" ]; then
    say_problem "JSend needs Python 3, but no working python3 was found on this Mac. macOS may offer the free Apple Command Line Tools install — open Terminal and run: python3 --version — and follow the prompt. Or install Python free from python.org, then open JSend again."
    exit 1
fi

if [ ! -f "$ENTRY" ]; then
    say_problem "JSend is incomplete: its app files were not found inside the bundle. Please download JSend again."
    exit 1
fi

echo "python3: $PY" >> "$LOG" 2>/dev/null

# --- run the app (the PC entry point opens the browser itself) ---------
"$PY" "$ENTRY" >> "$LOG" 2>&1
RC=$?
if [ "$RC" -ne 0 ] && [ "$RC" -ne 130 ] && [ "$RC" -ne 143 ]; then
    say_problem "JSend stopped with an error (code $RC). Details are in the log: $LOG"
fi
exit "$RC"
