#!/usr/bin/env bash
# Luminary desktop launcher for Linux.
#
# Starts the bundled server in single-user desktop mode on a free loopback port,
# waits for /api/health, then opens the UI in a chromeless app window (Chrome,
# Chromium, Edge, Brave or Vivaldi). Firefox, or the default browser, is the
# fallback.
#
#   ./luminary                 start and open the window
#   ./luminary --stop          stop the running server
#   ./luminary --status        report pid, URL, data folder and health
#   ./luminary --browser       open a normal browser tab instead
#   ./luminary --verify        check that this is a complete bundle
#   ./luminary --install       add Luminary to the applications menu
#   ./luminary --uninstall     remove that menu entry
#
# Everything the app writes lives in ~/.local/share/luminary (or $LUMINARY_DATA),
# never inside this folder, so the bundle can be moved or deleted safely.

set -u

SELF="$(readlink -f "${BASH_SOURCE[0]}")"
BUNDLE="$(dirname "$SELF")"
APP="$BUNDLE/app"
DATA_DIR="${LUMINARY_DATA:-${XDG_DATA_HOME:-$HOME/.local/share}/luminary}"
LOG_DIR="$DATA_DIR/logs"
PID_FILE="$DATA_DIR/luminary.pid"
RUNTIME_FILE="$DATA_DIR/runtime.json"
FIRST_PORT=8787
LAST_PORT=8887
WINDOW_MODE="${LUMINARY_WINDOW:-window}"

say() { printf '%s\n' "$*"; }
problem() { printf 'Luminary: %s\n' "$*" >&2; }

usage() {
  sed -n '2,18p' "$SELF" | sed 's/^# \{0,1\}//'
}

find_node() {
  if [ -x "$BUNDLE/runtime/bin/node" ]; then
    NODE="$BUNDLE/runtime/bin/node"
    return 0
  fi
  if command -v node >/dev/null 2>&1; then
    NODE="$(command -v node)"
    return 0
  fi
  problem "No Node runtime found: runtime/bin/node is missing and there is no node on PATH."
  problem "Download this bundle again, or install Node 24 (https://nodejs.org)."
  return 1
}

node_is_recent() {
  "$NODE" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null
}

port_free() {
  ! (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
}

choose_port() {
  local port="$FIRST_PORT"
  while [ "$port" -le "$LAST_PORT" ]; do
    if port_free "$port"; then
      printf '%s' "$port"
      return 0
    fi
    port=$((port + 1))
  done
  return 1
}

running_pid() {
  [ -f "$PID_FILE" ] || return 1
  local pid
  pid="$(cat "$PID_FILE" 2>/dev/null)"
  [ -n "$pid" ] || return 1
  kill -0 "$pid" 2>/dev/null || return 1
  printf '%s' "$pid"
}

current_port() {
  [ -f "$RUNTIME_FILE" ] || return 1
  sed -n 's/.*"port": *\([0-9][0-9]*\).*/\1/p' "$RUNTIME_FILE" | head -n 1
}

wait_health() {
  local url="http://127.0.0.1:$1/api/health" tries=0
  while [ "$tries" -lt 150 ]; do
    if "$NODE" -e "fetch('$url').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1; then
      return 0
    fi
    tries=$((tries + 1))
    sleep 0.2
  done
  return 1
}

verify_bundle() {
  local missing=0
  for rel in runtime/bin/node app/server/index.mjs app/dist/index.html luminary; do
    if [ ! -e "$BUNDLE/$rel" ]; then
      problem "missing: $rel"
      missing=1
    fi
  done
  if [ -d "$APP/node_modules" ]; then
    say "node_modules: present"
  else
    problem "missing: app/node_modules (production dependencies)"
    missing=1
  fi
  if [ "$missing" -ne 0 ]; then
    problem "This folder is not a complete Luminary bundle; extract the whole tarball."
    return 1
  fi
  say "Bundle:  $BUNDLE"
  say "Version: $(sed -n '1p' "$BUNDLE/version.txt" 2>/dev/null)"
  if find_node; then
    say "Node:    $("$NODE" --version 2>/dev/null) ($NODE)"
  fi
  return 0
}

start() {
  local pid port
  pid="$(running_pid)" && {
    port="$(current_port)"
    if [ -n "${port:-}" ]; then
      say "Luminary is already running at http://127.0.0.1:$port (pid $pid)."
      open_window "http://127.0.0.1:$port"
      return 0
    fi
    say "Luminary is already running (pid $pid)."
    return 0
  }

  verify_bundle >/dev/null || return 1
  find_node || return 1
  if ! node_is_recent; then
    problem "Node $("$NODE" --version 2>/dev/null) is too old; Luminary needs Node 24 or newer."
    return 1
  fi

  mkdir -p "$DATA_DIR" "$LOG_DIR" || {
    problem "could not create $DATA_DIR"
    return 1
  }
  chmod 700 "$DATA_DIR" 2>/dev/null || true

  port="$(choose_port)" || {
    problem "no free loopback port between $FIRST_PORT and $LAST_PORT"
    return 1
  }

  (
    cd "$APP" || exit 1
    LUMINARY_LOCAL=1 \
      PORT="$port" \
      HOST=127.0.0.1 \
      NODE_ENV=production \
      LUMINARY_DATA="$DATA_DIR" \
      nohup "$NODE" server/index.mjs >>"$LOG_DIR/server.out.log" 2>>"$LOG_DIR/server.err.log" &
    printf '%s\n' "$!" >"$PID_FILE"
  )

  pid="$(cat "$PID_FILE" 2>/dev/null)"
  if ! wait_health "$port"; then
    problem "the server did not answer on /api/health."
    problem "See $LOG_DIR/server.err.log, or run: cd \"$APP\" && \"$NODE\" server/index.mjs"
    return 1
  fi

  printf '{"pid": %s, "port": %s, "url": "http://127.0.0.1:%s", "data": "%s"}\n' \
    "$pid" "$port" "$port" "$DATA_DIR" >"$RUNTIME_FILE"

  say "Luminary is running at http://127.0.0.1:$port (pid $pid)"
  say "Data: $DATA_DIR"
  if [ "$WINDOW_MODE" = "browser" ]; then
    open_tab "http://127.0.0.1:$port"
  elif [ "$WINDOW_MODE" = "none" ]; then
    # Used by SMOKE-LINUX.sh: start the server but do not open anything.
    :
  else
    open_window "http://127.0.0.1:$port" || open_tab "http://127.0.0.1:$port"
  fi
  return 0
}

stop() {
  local pid
  if ! pid="$(running_pid)"; then
    rm -f "$PID_FILE" "$RUNTIME_FILE"
    say "Luminary is not running."
    return 0
  fi
  kill "$pid" 2>/dev/null
  local tries=0
  while kill -0 "$pid" 2>/dev/null && [ "$tries" -lt 50 ]; do
    tries=$((tries + 1))
    sleep 0.1
  done
  if kill -0 "$pid" 2>/dev/null; then
    kill -9 "$pid" 2>/dev/null
  fi
  rm -f "$PID_FILE" "$RUNTIME_FILE"
  say "Stopped Luminary (pid $pid)."
}

status() {
  local pid port
  say "Bundle: $BUNDLE"
  say "Data:   $DATA_DIR"
  if pid="$(running_pid)"; then
    port="$(current_port)"
    say "Status: running (pid $pid)"
    if [ -n "${port:-}" ]; then
      say "URL:    http://127.0.0.1:$port"
      find_node >/dev/null 2>&1 &&
        "$NODE" -e "fetch('http://127.0.0.1:$port/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1 &&
        say "Health: ok" || say "Health: unreachable"
    fi
  else
    say "Status: stopped"
  fi
  say "Logs:   $LOG_DIR"
}

browser_candidates() {
  printf '%s\n' google-chrome google-chrome-stable chromium chromium-browser \
    microsoft-edge microsoft-edge-stable brave-browser vivaldi-stable
}

open_window() {
  local url="$1" name browser
  while IFS= read -r name; do
    if browser="$(command -v "$name" 2>/dev/null)"; then
      say "Opening the app window with $name"
      setsid "$browser" \
        --app="$url" \
        --user-data-dir="$DATA_DIR/window-profile" \
        --class=Luminary \
        --no-first-run \
        --no-default-browser-check \
        >/dev/null 2>&1 &
      return 0
    fi
  done <<EOF
$(browser_candidates)
EOF
  if command -v firefox >/dev/null 2>&1; then
    say "No Chromium-based browser found; opening Firefox."
    setsid firefox --new-window "$url" >/dev/null 2>&1 &
    return 0
  fi
  return 1
}

open_tab() {
  local url="$1"
  if command -v xdg-open >/dev/null 2>&1; then
    setsid xdg-open "$url" >/dev/null 2>&1 &
    say "Opening $url in your browser."
    return 0
  fi
  say "Open $url in your browser."
  return 0
}

desktop_dir() {
  printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/applications"
}

icon_dir() {
  printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps"
}

install_menu_entry() {
  local apps icons entry
  apps="$(desktop_dir)"
  icons="$(icon_dir)"
  mkdir -p "$apps" "$icons" || {
    problem "could not create $apps"
    return 1
  }
  if [ -f "$BUNDLE/Luminary.png" ]; then
    cp "$BUNDLE/Luminary.png" "$icons/luminary.png"
  fi
  entry="$apps/luminary.desktop"
  cat >"$entry" <<EOF
[Desktop Entry]
Type=Application
Version=1.0
Name=Luminary
GenericName=Photo library
Comment=Photo library and raw editor
Exec="$SELF"
Path=$BUNDLE
Icon=$icons/luminary.png
Terminal=false
Categories=Graphics;Photography;
Keywords=photo;raw;catalog;editor;
StartupNotify=true
StartupWMClass=Luminary
EOF
  chmod +x "$entry"
  if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$apps" >/dev/null 2>&1 || true
  fi
  say "Added Luminary to your applications menu: $entry"
  say "If it does not appear yet, log out and back in."
}

uninstall_menu_entry() {
  local entry
  entry="$(desktop_dir)/luminary.desktop"
  rm -f "$entry"
  rm -f "$(icon_dir)/luminary.png"
  if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$(desktop_dir)" >/dev/null 2>&1 || true
  fi
  say "Removed the menu entry. Your photos and catalog in $DATA_DIR were kept."
}

case "${1:-}" in
  ""|--start)
    start
    ;;
  --stop)
    stop
    ;;
  --status)
    status
    ;;
  --browser)
    WINDOW_MODE=browser
    start
    ;;
  --verify)
    verify_bundle
    ;;
  --install)
    install_menu_entry
    ;;
  --uninstall)
    uninstall_menu_entry
    ;;
  --help|-h)
    usage
    ;;
  *)
    problem "unknown option $1"
    usage >&2
    exit 2
    ;;
esac
