#!/usr/bin/env bash
# Generated by https://manifoldone.com/install.sh (server-rendered)
MANIFOLDONE_TOKEN=""
MANIFOLDONE_MEMORY_URL="https://manifoldone.ai"
# Manifoldone — the agent-native work platform.
# Plan 6.C.4 — curl-able cross-platform installer.
#
# Usage:
#   curl -fsSL https://manifoldone.com/install.sh | sh
#
# What it does:
#   1. Detects OS (Darwin / Linux / MINGW-WSL) and architecture.
#   2. macOS arm64+x86_64 — downloads the matching .app.tar.gz from the
#      latest GitHub Release, extracts to /Applications/Manifoldone.app,
#      removes Gatekeeper quarantine, and launches.
#   3. Linux + Windows — prints a friendly "coming in v0.6" message that
#      links to the manual download page.
#
# Served by the Astro server route at sites/landing/src/pages/install.sh.ts
# (Plan 2026-05-26 F.1). The route prepends `MANIFOLDONE_TOKEN=…` /
# `MANIFOLDONE_MEMORY_URL=…` env vars when a valid `?token=ci_…` query is
# present so the `fire_connect_intent` block at the bottom can drop the
# connect-intent file + fire the `manifoldone://connect` deeplink.
#
# Anonymous `curl https://manifoldone.com/install.sh | sh` still works — the
# preamble vars are empty strings and the conditional block stays dormant.
#
# Design notes:
#   - Plain bash, no jq dependency. We grep the GitHub API for the asset
#     URL so a fresh macOS install with no extras can run this.
#   - Release URL discovery uses
#     `https://api.github.com/repos/<owner>/<repo>/releases/latest`. If
#     no release is published yet, the script halts with a clear "no
#     release published yet — check back soon" message.
#   - We never `eval` API output and we always quote substitutions.

set -euo pipefail

# --- Config ---------------------------------------------------------------

# Desktop bundles are hosted on the landing site (manifoldone.com); the
# GitHub repo stays private. Release artifacts live under
# `sites/landing/public/releases/<version>/Manifoldone-<arch>.app.tar.gz`.
RELEASE_VERSION="${MANIFOLDONE_RELEASE_VERSION:-v0.2.0-alpha.1}"
RELEASE_BASE="${MANIFOLDONE_RELEASE_BASE:-https://manifoldone.com/releases/${RELEASE_VERSION}}"
APP_NAME="Manifoldone"
APP_BUNDLE="/Applications/${APP_NAME}.app"
INSTALL_LOG="${HOME}/.manifoldone/install.log"

# --- ANSI helpers ---------------------------------------------------------
# Auto-disable colors when not on a TTY (e.g. piped, CI).
if [[ -t 1 ]]; then
  C_RESET=$'\033[0m'; C_BOLD=$'\033[1m'
  C_CYAN=$'\033[36m'; C_YELLOW=$'\033[33m'; C_RED=$'\033[31m'; C_GREEN=$'\033[32m'
else
  C_RESET=""; C_BOLD=""; C_CYAN=""; C_YELLOW=""; C_RED=""; C_GREEN=""
fi

info()  { printf "%s%s%s %s\n" "${C_CYAN}" "==>" "${C_RESET}" "$*"; }
warn()  { printf "%s%s%s %s\n" "${C_YELLOW}" "WARN" "${C_RESET}" "$*" >&2; }
err()   { printf "%s%s%s %s\n" "${C_RED}" "ERR " "${C_RESET}" "$*" >&2; }
ok()    { printf "%s%s%s %s\n" "${C_GREEN}" "OK  " "${C_RESET}" "$*"; }

# --- Detect OS + arch -----------------------------------------------------

detect_platform() {
  local kernel arch
  kernel="$(uname -s)"
  arch="$(uname -m)"

  case "${kernel}" in
    Darwin)
      case "${arch}" in
        arm64) echo "darwin-aarch64" ;;
        x86_64) echo "darwin-x86_64" ;;
        *) echo "darwin-unknown-${arch}" ;;
      esac
      ;;
    Linux)
      case "${arch}" in
        x86_64) echo "linux-x86_64" ;;
        aarch64|arm64) echo "linux-aarch64" ;;
        *) echo "linux-unknown-${arch}" ;;
      esac
      ;;
    MINGW*|MSYS*|CYGWIN*)
      echo "windows-${arch}"
      ;;
    *)
      echo "unknown-${kernel}-${arch}"
      ;;
  esac
}

# --- Locate the matching asset URL ----------------------------------------

# Returns the download URL for the .app tarball matching the given platform.
# Empty stdout = unsupported platform.
asset_url_for_platform() {
  local platform="$1"
  case "${platform}" in
    darwin-aarch64) echo "${RELEASE_BASE}/Manifoldone-aarch64.app.tar.gz" ;;
    darwin-x86_64)  echo "${RELEASE_BASE}/Manifoldone-x64.app.tar.gz" ;;
    *) ;;
  esac
}

# --- macOS install --------------------------------------------------------

install_macos() {
  local platform="$1"
  local url
  url="$(asset_url_for_platform "${platform}")"
  if [[ -z "${url}" ]]; then
    err "No desktop bundle published for ${platform} yet."
    err "Supported: darwin-aarch64 (Apple Silicon)."
    exit 1
  fi

  info "Platform: ${platform}"
  info "Download:  ${url}"
  local tmpdir
  tmpdir="$(mktemp -d -t manifoldone.XXXXXX)"
  trap 'rm -rf "${tmpdir}"' EXIT

  curl -fL --progress-bar -o "${tmpdir}/manifoldone.tar.gz" "${url}"

  info "Extracting to /Applications"
  if [[ -d "${APP_BUNDLE}" ]]; then
    info "Replacing existing ${APP_BUNDLE}"
    rm -rf "${APP_BUNDLE}"
  fi
  tar -xzf "${tmpdir}/manifoldone.tar.gz" -C "/Applications"
  if [[ ! -d "${APP_BUNDLE}" ]]; then
    err "Tarball didn't contain ${APP_NAME}.app — bundle layout changed?"
    exit 1
  fi

  # Strip the quarantine xattr so Gatekeeper doesn't block the first
  # launch when the bundle is unsigned. Real signed builds skip this
  # cleanly; xattr exits 0 either way.
  xattr -dr com.apple.quarantine "${APP_BUNDLE}" 2>/dev/null || true

  ok "Installed ${APP_BUNDLE}"
  info "Launching ${APP_NAME}…"
  open -a "${APP_NAME}" || warn "open failed; launch manually from /Applications"

  printf "\n%sNext step:%s the app prompts you to install the %smanifoldone%s CLI in your PATH on first launch.\n" \
    "${C_BOLD}" "${C_RESET}" "${C_CYAN}" "${C_RESET}"
}

# --- Linux fallback -------------------------------------------------------

install_linux() {
  local platform="$1"
  warn "Linux installer is on the ramp."
  cat <<EOM

Manifoldone Linux bundles (.deb / .rpm / AppImage) ship in v0.6.

For now, you can:
  - CLI-only headless install: curl https://manifoldone.com/cli.sh
  - Track progress:           https://manifoldone.com/install
  - Detected platform:        ${platform}

If you'd like to be notified when Linux is ready, drop a line to
hello@manifoldone.com — we ship to early-list folks first.
EOM
}

# --- Windows fallback -----------------------------------------------------

install_windows() {
  local platform="$1"
  warn "Windows installer is on the ramp."
  cat <<EOM

Manifoldone for Windows (.msi) ships in v0.6.

For now:
  - Manual download: https://manifoldone.com/install
  - Detected platform: ${platform}

WSL users: you can run this script inside WSL to install the Linux
build (also still on the ramp).
EOM
}

# --- Main -----------------------------------------------------------------

main() {
  printf "%s%s installer%s — https://manifoldone.com\n\n" \
    "${C_BOLD}" "${APP_NAME}" "${C_RESET}"

  local platform
  platform="$(detect_platform)"
  info "Detected platform: ${platform}"

  mkdir -p "$(dirname "${INSTALL_LOG}")"

  case "${platform}" in
    darwin-aarch64|darwin-x86_64)
      install_macos "${platform}"
      ;;
    linux-*)
      install_linux "${platform}"
      ;;
    windows-*)
      install_windows "${platform}"
      ;;
    *)
      err "Unsupported platform: ${platform}"
      err "Open an issue at https://github.com/${REPO_OWNER}/${REPO_NAME}/issues"
      exit 1
      ;;
  esac
}

# --- Connect-intent + deeplink (server-rendered install.sh only) ---------
#
# Plan 2026-05-26 onboarding & machine pairing redesign — F.1.
# When the server-rendered install.sh injected a MANIFOLDONE_TOKEN at the top
# of this script, drop the connect-intent file the Tauri app picks up on first
# boot, then fire the manifoldone://connect deeplink so the freshly-installed
# app self-pairs without the user touching another button.
#
# Anonymous `curl …/install.sh | sh` runs (no token) skip this block entirely
# because the env var either isn't set or is the empty string.
fire_connect_intent() {
  if [ -z "${MANIFOLDONE_TOKEN:-}" ]; then
    return 0
  fi

  local memory_url="${MANIFOLDONE_MEMORY_URL:-https://manifoldone.ai}"
  local intent_dir="${HOME}/.manifoldone"
  local intent_file="${intent_dir}/connect-intent.json"

  mkdir -p "${intent_dir}"
  umask 077
  cat > "${intent_file}" <<EOF
{
  "token": "${MANIFOLDONE_TOKEN}",
  "memory_url": "${memory_url}",
  "written_at": "$(date -u +%FT%TZ)"
}
EOF
  ok "Wrote connect-intent to ${intent_file}"

  # URL-encode the memory URL for the deeplink query string.
  # Prefer jq if available; fall back to python3 (macOS ships it); skip if both missing.
  local enc_memory
  if command -v jq >/dev/null 2>&1; then
    enc_memory="$(printf %s "${memory_url}" | jq -sRr @uri)"
  elif command -v python3 >/dev/null 2>&1; then
    enc_memory="$(python3 -c 'import urllib.parse,sys;print(urllib.parse.quote(sys.stdin.read()))' <<< "${memory_url}")"
  else
    enc_memory="${memory_url}"
  fi

  local deeplink="manifoldone://connect?token=${MANIFOLDONE_TOKEN}&memory=${enc_memory}"
  info "Firing deeplink ${deeplink}"
  case "$(uname -s)" in
    Darwin) open "${deeplink}" 2>/dev/null || warn "open failed — launch Manifoldone manually and the connect-intent file will be picked up on first boot." ;;
    Linux)  xdg-open "${deeplink}" 2>/dev/null || warn "xdg-open failed — launch Manifoldone manually and the connect-intent file will be picked up on first boot." ;;
    *)      : ;;  # Windows path handled separately; the .msi installer registers the scheme
  esac
}

# Allow this file to be sourced for unit tests (detect_platform +
# asset_url_for_platform). When sourced, BASH_SOURCE != $0.
if [[ "${BASH_SOURCE[0]:-$0}" == "${0}" ]]; then
  main "$@"
  fire_connect_intent
fi
