#!/usr/bin/env bash
# Install Linggen.app on macOS via curl-pipe.
#
# Linggen is the unified app — it hosts every Linggen app (Mac Shifu (formerly Sys Doctor), CFO,
# Pulse, …) as tabs in one launcher, on the shared local daemon.
#
# Why curl + tarball, not a DMG?
#   macOS attaches a quarantine xattr to anything downloaded by a browser
#   (Arc, Safari, Chrome, …). Without an Apple Developer ID signature,
#   Gatekeeper then refuses to launch the app with "is damaged". curl /
#   wget / scp do NOT attach the quarantine flag, so an unsigned binary
#   pulled this way runs without any "damaged" warning.
#
# Usage:
#   curl -fsSL https://linggen.dev/install-app.sh | bash
#   curl -fsSL https://linggen.dev/install-app.sh | bash -s -- --version linggen-v0.1.0
#
# NOTE: the default (no --version) resolves the latest PUBLISHED linggen-v*
# release. A draft release is not visible to the public API — pass
# --version linggen-v<x.y.z> to target a specific (e.g. draft) tag.

set -euo pipefail

if [ -n "${FISH_VERSION:-}" ]; then
  echo "This script is bash-only. Run: bash install-app.sh"
  exit 1
fi

REPO="${LINGGEN_RELEASE_REPO:-linggen/linggen-releases}"
APP_NAME="Linggen"
APP_DIR="/Applications/${APP_NAME}.app"
TAG_PREFIX="linggen-v"

VERSION_ARG=""
SKIP_LAUNCH=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    --version)     VERSION_ARG="$2"; shift 2 ;;
    --no-launch)   SKIP_LAUNCH=true; shift ;;
    -h|--help)
      sed -n '2,22p' "$0" | sed 's/^# \?//'
      exit 0 ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

# --- Detect target arch ---
arch="$(uname -m)"
case "$(uname -s)" in
  Darwin)
    case "$arch" in
      arm64|aarch64) target="darwin-arm64" ;;
      *) echo "Linggen currently ships Apple Silicon only. Detected: $arch" >&2; exit 1 ;;
    esac ;;
  *) echo "Linggen is macOS-only. Detected: $(uname -s)" >&2; exit 1 ;;
esac

# --- Resolve version ---
# If --version is "linggen-vX.Y.Z", strip the prefix; if just "X.Y.Z", use as-is.
# If omitted, query GitHub API for the latest linggen-v* release tag.
resolve_version() {
  if [ -n "$VERSION_ARG" ]; then
    echo "${VERSION_ARG#${TAG_PREFIX}}"
    return
  fi
  # latest linggen-v* release (drafts excluded by the public API)
  local tag
  tag=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases" \
        | grep -oE "\"tag_name\": *\"${TAG_PREFIX}[^\"]+\"" \
        | head -1 \
        | sed -E 's/.*"'"${TAG_PREFIX}"'([^"]+)".*/\1/')
  if [ -z "$tag" ]; then
    echo "Could not find a published linggen-v* release on ${REPO}." >&2
    echo "Pass --version <ver> to install a specific (e.g. draft) tag." >&2
    exit 1
  fi
  echo "$tag"
}

VERSION=$(resolve_version)
TAG="${TAG_PREFIX}${VERSION}"
ASSET="linggen-${VERSION}-${target}.tar.gz"
URL="https://github.com/${REPO}/releases/download/${TAG}/${ASSET}"

echo "==> Installing ${APP_NAME} ${VERSION} (${target})"
echo "    from ${URL}"

# --- Quit any running copy so we can overwrite ---
if pgrep -f "/${APP_NAME}.app/Contents/MacOS/" >/dev/null 2>&1; then
  echo "==> ${APP_NAME} is running — quitting"
  osascript -e "tell application \"${APP_NAME}\" to quit" 2>/dev/null || true
  sleep 1
  pkill -f "/${APP_NAME}.app/Contents/MacOS/" 2>/dev/null || true
fi

# --- Remove old copy if present ---
# A prior install may be owned by root (e.g. installed with sudo, or a legacy
# build). Fall back to sudo so the replace doesn't die on "Permission denied".
if [ -d "$APP_DIR" ]; then
  echo "==> Replacing existing ${APP_DIR}"
  if ! rm -rf "$APP_DIR" 2>/dev/null; then
    echo "==> Existing ${APP_NAME}.app is owned by another user — using sudo to remove it"
    sudo rm -rf "$APP_DIR"
  fi
fi

# --- Download + extract straight into /Applications ---
# /Applications is admin-group writable on default macOS installs; sudo only
# kicks in if the user has restricted it.
TMPDIR_NEW=$(mktemp -d)
trap 'rm -rf "$TMPDIR_NEW"' EXIT
echo "==> Downloading + extracting…"
if ! curl -fL --retry 3 "$URL" | tar -xz -C "$TMPDIR_NEW"; then
  echo "Download failed." >&2
  echo "Check the version exists at https://github.com/${REPO}/releases" >&2
  exit 1
fi

if [ ! -d "${TMPDIR_NEW}/${APP_NAME}.app" ]; then
  echo "Extracted archive does not contain ${APP_NAME}.app — bad release artifact?" >&2
  exit 1
fi

if ! mv "${TMPDIR_NEW}/${APP_NAME}.app" "$APP_DIR" 2>/dev/null; then
  echo "==> Need sudo to write to /Applications"
  sudo mv "${TMPDIR_NEW}/${APP_NAME}.app" "$APP_DIR"
fi

# Belt-and-braces — strip any quarantine attr that may have hitchhiked in.
xattr -dr com.apple.quarantine "$APP_DIR" 2>/dev/null || true

echo "==> Installed to ${APP_DIR}"

if [ "$SKIP_LAUNCH" = "false" ]; then
  echo "==> Launching"
  open "$APP_DIR"
fi
