#!/usr/bin/env bash
# GhostWriter — one-shot installer for macOS (Next Client AI static host)
#
#   curl -fsSL https://sites.nextclientai.com/ghostwriter/install.sh | bash
#
# Upload these five files to the same folder on your server:
#   install.sh  ghostwriter.swift  ghostwriter.html  start.command  README.md
#
# Override base URL if needed:
#   curl -fsSL https://sites.nextclientai.com/ghostwriter/install.sh | GHOSTWRITER_DIST_BASE='https://other.example/ghostwriter/' bash

set -euo pipefail

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "GhostWriter only supports macOS."
  exit 1
fi

DEFAULT_BASE="https://sites.nextclientai.com/ghostwriter/"
BASE="${GHOSTWRITER_DIST_BASE:-$DEFAULT_BASE}"
[[ "${BASE}" == */ ]] || BASE="${BASE}/"

DEST="${HOME}/GhostWriter"
FILES=(ghostwriter.swift ghostwriter.html start.command README.md)

echo ""
echo "  GhostWriter — installing to ${DEST}"
echo "  (from ${BASE})"
echo ""

if ! command -v curl >/dev/null 2>&1; then
  echo "[!] curl not found."
  exit 1
fi

mkdir -p "${DEST}"

for f in "${FILES[@]}"; do
  echo "[*] Downloading ${f}..."
  if ! curl -fsSL "${BASE}${f}" -o "${DEST}/${f}.part"; then
    rm -f "${DEST}/${f}.part"
    echo ""
    echo "[!] Failed: ${BASE}${f}"
    echo "    Upload all five files to ${DEFAULT_BASE} (see header in install.sh)."
    echo "    On your Mac:  cd ~/Desktop/MiniApps && bash scripts/ghostwriter/package-for-site.sh"
    echo ""
    exit 1
  fi
  mv "${DEST}/${f}.part" "${DEST}/${f}"
done

chmod +x "${DEST}/start.command"
xattr -dr com.apple.quarantine "${DEST}" 2>/dev/null || true

echo ""
echo "  Done. Opening ${DEST} in Finder."
echo "  → Double-click start.command"
echo "  → Grant Accessibility to Terminal (System Settings → Privacy & Security → Accessibility)"
echo "  → If build fails, run: xcode-select --install"
echo ""

open "${DEST}"
