#!/bin/sh
# pruse — open the current repo (or one of its PRs) in the pruse app.
set -e

usage() {
  cat <<USAGE
Usage:
  pruse            open the repo in the current directory
  pruse <number>   open that PR
  pruse diff       open the local changes of the worktree in the current directory
  pruse inbox      list the repo's open PRs in the terminal
  pruse clean      remove worktrees and refs of closed/merged PRs (--dry-run to preview)
  pruse doctor     check git, gh and the current repo
USAGE
}

ROOT="$(cd "$(dirname "$(realpath "$0")")/.." && pwd)"

# Inside Pruse.app (Contents/Resources/app/bin/pruse), use the app's own Electron, also as Node for
# the terminal commands; in the repo, the dev build and system Node.
APP_EXE="$ROOT/../../MacOS/Electron"
if [ -x "$APP_EXE" ]; then
  ELECTRON="$APP_EXE"
  APP_ARG=""
  cli() { ELECTRON_RUN_AS_NODE=1 exec "$ELECTRON" "$ROOT/out/main/cli.js" "$@"; }
else
  if [ ! -f "$ROOT/out/main/index.js" ]; then
    echo "pruse: app not built. Run 'npm run build' in $ROOT" >&2
    exit 1
  fi
  ELECTRON="$(node -p "require('$ROOT/node_modules/electron')")"
  APP_ARG="$ROOT"
  cli() { exec node "$ROOT/out/main/cli.js" "$@"; }
fi

PR=""
case "${1:-}" in
  "") ;;
  diff) LOCAL=1 ;;
  doctor|inbox|clean) CMD="$1"; shift; cli "$CMD" "$PWD" "$@" ;;
  -h|--help|help) usage; exit 0 ;;
  *[!0-9]*) echo "pruse: unknown argument '$1'" >&2; usage >&2; exit 2 ;;
  *) PR="$1" ;;
esac

# Run the Electron binary directly (not the npm wrapper) and detach from the terminal.
# If pruse is already running, this instance hands over the target and exits.
nohup "$ELECTRON" ${APP_ARG:+"$APP_ARG"} "--pruse-repo=$PWD" ${PR:+"--pruse-pr=$PR"} ${LOCAL:+"--pruse-local"} >/dev/null 2>&1 &
