#!/bin/bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../Resources" && pwd)"
APP_BUNDLE="$(cd "$(dirname "$0")/../.." && pwd)"
LOG="$HOME/Library/Logs/dj-voting-rekordbox-sync.log"
UI="http://127.0.0.1:9478/"
mkdir -p "$(dirname "$LOG")"
echo "==== $(date) launcher path=$APP_BUNDLE ====" >>"$LOG"

ui_is_up() {
  /usr/bin/curl -fsS --max-time 1 "$UI" >/dev/null 2>&1
}

kill_previous_ui() {
  pkill -f "DJ Voting Rekordbox Sync.app/Contents/Resources/ui/settings-server.mjs" 2>/dev/null || true
  local pids
  pids="$(lsof -t -nP -iTCP:9478 -sTCP:LISTEN 2>/dev/null || true)"
  if [[ -n "${pids:-}" ]]; then
    # shellcheck disable=SC2086
    kill -9 $pids 2>/dev/null || true
  fi
  sleep 0.2
}

canonical() {
  (cd "$1" && pwd -P) 2>/dev/null || printf '%s\n' "$1"
}

is_stable_location() {
  local p desktop home_apps support
  p="$(canonical "$1")"
  desktop="$(canonical "$HOME/Desktop")"
  home_apps="$(canonical "$HOME/Applications")"
  support="$(canonical "$HOME/Library/Application Support/DJ Voting")"
  case "$p" in
    "$desktop"|"$desktop"/*) return 0 ;;
    /Applications|/Applications/*) return 0 ;;
    "$home_apps"|"$home_apps"/*) return 0 ;;
    "$support"|"$support"/*) return 0 ;;
  esac
  return 1
}

drop_quarantine() {
  local p="$1"
  xattr -dr com.apple.quarantine "$p" 2>/dev/null || true
  local parent
  parent="$(dirname "$p")"
  if [[ "$parent" != "/" && "$parent" != "$HOME" && "$parent" != "$HOME/Desktop" && "$parent" != "/Applications" ]]; then
    xattr -dr com.apple.quarantine "$parent" 2>/dev/null || true
  fi
}

relaunch_at() {
  local dest="$1"
  drop_quarantine "$dest"
  kill_previous_ui
  # Never „open“ the .app — Gatekeeper blocks unnotarized bundles via LaunchServices.
  echo "translocation: launching via bash launcher (no open .app)" >>"$LOG"
  exec bash "$dest/Contents/MacOS/launcher"
}

resolve_original_app() {
  local helper orig found t best="" best_t=0
  local roots=()
  helper="$(cd "$(dirname "$0")" && pwd)/translocation-origin"
  if [[ -x "$helper" ]]; then
    orig="$("$helper" "$APP_BUNDLE" 2>>"$LOG" || true)"
    orig="${orig//$'\n'/}"
    if [[ -n "$orig" && -d "$orig" ]]; then
      printf '%s\n' "$orig"
      return 0
    fi
  fi
  [[ -d "$HOME/Desktop" ]] && roots+=("$HOME/Desktop")
  [[ -d /Applications ]] && roots+=(/Applications)
  [[ -d "$HOME/Applications" ]] && roots+=("$HOME/Applications")
  [[ ${#roots[@]} -gt 0 ]] || return 1
  while IFS= read -r found; do
    [[ -n "$found" ]] || continue
    case "$found" in */AppTranslocation/*) continue ;; esac
    t="$(stat -f %m "$found" 2>/dev/null || echo 0)"
    if [[ "$t" -ge "$best_t" ]]; then
      best="$found"
      best_t="$t"
    fi
  done < <(/usr/bin/find "${roots[@]}" -maxdepth 5 -name "DJ Voting Rekordbox Sync.app" -type d 2>/dev/null || true)
  if [[ -n "$best" ]]; then
    printf '%s\n' "$best"
    return 0
  fi
  return 1
}

# Gatekeeper copies quarantined apps to AppTranslocation even when they already
# sit on the Desktop (e.g. inside the unzipped folder). Resolve that original
# path first — only copy to Desktop if the user launched from Downloads/ZIP.
if [[ "$APP_BUNDLE" == *"/AppTranslocation/"* ]]; then
  ORIG="$(resolve_original_app || true)"
  echo "translocation: original=${ORIG:-unknown}" >>"$LOG"
  if [[ -n "${ORIG:-}" && -d "$ORIG" ]] && is_stable_location "$ORIG"; then
    echo "translocation: already on Desktop/Applications — not copying" >>"$LOG"
    drop_quarantine "$ORIG"
  else

  DEST="$HOME/Desktop/DJ Voting Rekordbox Sync.app"
  osascript <<'OSA' >/dev/null 2>&1 || true
display dialog "Die App liegt noch in Downloads. Sie wird auf den Schreibtisch kopiert.

Danach das Icon auf dem Schreibtisch öffnen (nicht die Datei in Downloads)." buttons {"OK"} default button 1 with title "DJ Voting Rekordbox Sync"
OSA
  if [[ -d "$DEST" ]]; then
    echo "translocation: replacing Desktop copy" >>"$LOG"
    rm -rf "$DEST"
  fi
  echo "translocation: copying to Desktop" >>"$LOG"
  if ! ditto "$APP_BUNDLE" "$DEST" 2>>"$LOG"; then
    osascript -e 'display dialog "Kopieren auf den Schreibtisch fehlgeschlagen. Bitte die App manuell auf den Schreibtisch oder nach Programme legen und von dort öffnen." buttons {"OK"} default button 1 with title "DJ Voting Rekordbox Sync"' >/dev/null 2>&1 || true
    exit 1
  fi
  relaunch_at "$DEST"
  fi
fi

# Icon clicked while the server is already in the background → just reopen UI.
if ui_is_up; then
  echo "UI already up — reopening $UI" >>"$LOG"
  /usr/bin/open "$UI" >>"$LOG" 2>&1 || true
  exit 0
fi

kill_previous_ui

export DJ_VOTING_APP_ROOT="$ROOT"
export DJ_VOTING_UI_PORT=9478
cd "$ROOT/ui"
exec "$ROOT/bridge/node" ./settings-server.mjs >>"$LOG" 2>&1
