#!/usr/bin/env bash
# FathomDB installer — curl -fsSL https://fathomdb.dev/install.sh | bash
#
# Downloads the latest build from downloads.fathomdb.dev, installs the app
# (macOS → the .dmg into /Applications, Linux → the AppImage into
# ~/.local/share/fathomdb), and puts the `fathom` and `fdb` commands in
# ~/.local/bin. Per-user, no sudo, no account. Read it before you run it.
set -euo pipefail

BASE="https://downloads.fathomdb.dev"
BIN_DIR="${HOME}/.local/bin"

info() { printf '\033[36m%s\033[0m\n' "$*"; }
err() { printf '\033[31m%s\033[0m\n' "$*" >&2; exit 1; }

os="$(uname -s)"
arch="$(uname -m)"
info "Installing FathomDB for ${os} ${arch}…"
command -v curl >/dev/null || err "curl is required."

case "$os" in
  Darwin)
    file="$([ "$arch" = "arm64" ] && echo FathomDB-arm64.dmg || echo FathomDB-x64.dmg)"
    tmp="$(mktemp -d)"
    mnt=""
    # Always detach the volume and remove the temp dir — even if a step below
    # fails or errors out — so a failed install never leaks a mounted DMG.
    cleanup() { [ -n "$mnt" ] && hdiutil detach -quiet "$mnt" >/dev/null 2>&1; rm -rf "$tmp"; return 0; }
    trap cleanup EXIT
    info "Downloading ${file} (~160 MB)…"
    curl -fSL --progress-bar "${BASE}/${file}" -o "$tmp/FathomDB.dmg" || err "Download failed. See https://fathomdb.dev/download"
    info "Installing to /Applications…"
    # Mount via -plist and read the mount-point from it. The old `-quiet | grep`
    # approach printed nothing (so grep matched nothing and the script died under
    # `set -e` before it could report why), and the volume name has a space that
    # a whitespace-delimited regex would truncate. Capturing the plist first also
    # keeps a mount failure from dying inside a pipeline.
    plist="$(hdiutil attach -nobrowse -readonly -plist "$tmp/FathomDB.dmg")" \
      || err "Couldn't mount the disk image. See https://fathomdb.dev/download"
    mnt="$(printf '%s\n' "$plist" \
      | awk -F'[<>]' '/<key>mount-point<\/key>/{getline; if ($0 ~ /<string>/){print $3; exit}}')"
    [ -n "$mnt" ] || err "Mounted the image but couldn't find its volume."
    [ -d "$mnt/FathomDB.app" ] || err "The disk image didn't contain FathomDB.app."
    rm -rf "/Applications/FathomDB.app"
    cp -R "$mnt/FathomDB.app" /Applications/ || err "Couldn't copy FathomDB.app into /Applications."
    # Unsigned for now — clear quarantine so Gatekeeper doesn't block first launch.
    xattr -dr com.apple.quarantine /Applications/FathomDB.app 2>/dev/null || true
    launcher="/Applications/FathomDB.app/Contents/MacOS/FathomDB"
    ;;
  Linux)
    dest="${HOME}/.local/share/fathomdb"
    mkdir -p "$dest"
    info "Downloading FathomDB.AppImage (~140 MB)…"
    curl -fSL --progress-bar "${BASE}/FathomDB.AppImage" -o "$dest/FathomDB.AppImage" || err "Download failed. See https://fathomdb.dev/download"
    chmod +x "$dest/FathomDB.AppImage"
    launcher="$dest/FathomDB.AppImage"
    ;;
  *)
    err "Unsupported OS: ${os}. See https://fathomdb.dev/download"
    ;;
esac

# The fathom / fdb commands. This mirrors the app's own routing (isHeadlessArgs):
# a subcommand — anything starting with a letter, plus the help/version flags —
# runs headless in the foreground so its output (or its "unknown command" error)
# reaches the terminal; a bare launch, the explicit `open` verb, and any other
# flag/path open the GUI detached so the prompt returns.
# NODE_NO_WARNINGS silences noisy transitive-dep warnings.
mkdir -p "$BIN_DIR"
for name in fathom fdb; do
  cat > "${BIN_DIR}/${name}" <<SHIM
#!/bin/sh
case "\$1" in
  open|'')
    NODE_NO_WARNINGS=1 "${launcher}" "\$@" >/dev/null 2>&1 &
    ;;
  --help|-h|--version|-v|[A-Za-z]*)
    NODE_NO_WARNINGS=1 exec "${launcher}" "\$@" ;;
  *)
    NODE_NO_WARNINGS=1 "${launcher}" "\$@" >/dev/null 2>&1 &
    ;;
esac
SHIM
  chmod +x "${BIN_DIR}/${name}"
done

info "Installed. 'fathom' and 'fdb' are in ${BIN_DIR}."
case ":${PATH}:" in
  *":${BIN_DIR}:"*) : ;;
  *) info "Add it to your PATH:  echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.zshrc && source ~/.zshrc" ;;
esac
info "Launch the app:  fathom      ·      browse from the terminal:  fathom ls"
