#!/usr/bin/env bash
# Bearhole one-click installer for macOS & Linux — for people who have never
# touched npm/pear/a terminal. It:
#   1. asks where to install (with a sensible default),
#   2. makes sure the Pear runtime exists (installs a private Node + Pear if not),
#   3. creates a real launcher with the Bearhole icon (a .app on macOS, a
#      .desktop entry on Linux) — the icon workaround, since `pear run` otherwise
#      shows the generic Pear logo,
#   4. launches Bearhole.
#
# Runs on a DEFAULT install of macOS and Ubuntu/Debian/Fedora/etc:
#   * needs only bash + tar + (curl OR wget) — all present out of the box,
#   * if npm isn't installed it downloads a private, throwaway copy of Node just
#     for Bearhole — nothing system-wide, nothing needs sudo.
#
# Run it:  bash bearhole-install.sh      (or double-click bearhole-install.command)
set -euo pipefail

LINK="pear://9jumqiujkww7aewmgkumqun4h3cusknjpfhohdyejbbcptb7h31o"
NODE_VERSION="${BEARHOLE_NODE_VERSION:-v20.18.1}"   # private Node used only if npm is missing
SITE="${BEARHOLE_SITE:-https://bearhole.dk}"        # where the icon assets live
BOLD=$'\e[1m'; TEAL=$'\e[36m'; DIM=$'\e[2m'; RED=$'\e[31m'; NC=$'\e[0m'

say  () { printf '%s\n' "$*"; }
step () { printf '%s\n' "${TEAL}${BOLD}==>${NC} ${BOLD}$*${NC}"; }
warn () { printf '%s\n' "${RED}$*${NC}"; }

# download <url> <dest> — works with either curl or wget (Ubuntu ships wget, not curl)
download () {
  if command -v curl >/dev/null 2>&1; then curl -fSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -q "$1" -O "$2"
  else warn "Need 'curl' or 'wget' to download. Install one and re-run."; exit 1; fi
}

# ---- detect platform -------------------------------------------------------
OS="$(uname -s)"; ARCH="$(uname -m)"
case "$OS" in
  Darwin) PLAT=darwin ;;
  Linux)  PLAT=linux ;;
  *) warn "Unsupported OS: $OS. Use the Windows installer or the manual steps on $SITE."; exit 1 ;;
esac
case "$ARCH" in
  x86_64|amd64) NARCH=x64 ;;
  arm64|aarch64) NARCH=arm64 ;;
  *) warn "Unsupported CPU: $ARCH."; exit 1 ;;
esac

clear 2>/dev/null || true
say "${BOLD}${TEAL}Bearhole installer${NC} — peer-to-peer, no account, no cloud."
say "${DIM}This sets up Bearhole on your computer. It won't touch anything system-wide.${NC}"
say ""

# ---- 1. where to install ---------------------------------------------------
if [ "$PLAT" = darwin ]; then DEFAULT_DIR="$HOME/Applications/Bearhole"; else DEFAULT_DIR="$HOME/.local/share/bearhole"; fi
DIR="${BEARHOLE_DIR:-}"
if [ -z "$DIR" ]; then
  if [ -t 0 ]; then
    printf '%s' "${BOLD}Where should Bearhole be installed?${NC} ${DIM}[$DEFAULT_DIR]${NC} "
    read -r DIR || true
  fi
  DIR="${DIR:-$DEFAULT_DIR}"
fi
case "$DIR" in "~"/*) DIR="$HOME/${DIR#~/}" ;; esac   # expand a leading ~
mkdir -p "$DIR"
step "Installing into $DIR"

# ---- 2. ensure a `pear` command -------------------------------------------
PEAR=""
if command -v pear >/dev/null 2>&1; then
  PEAR="$(command -v pear)"
  step "Found Pear already installed."
else
  if command -v npm >/dev/null 2>&1; then
    NPM="$(command -v npm)"
    step "Using your Node/npm to install Pear."
  else
    step "No Node found — downloading a private copy just for Bearhole (no sudo)."
    NODE_DIR="$DIR/node"
    if [ ! -x "$NODE_DIR/bin/node" ]; then
      # .tar.gz for both platforms → only needs gzip (no xz), present everywhere
      TARBALL="node-${NODE_VERSION}-${PLAT}-${NARCH}.tar.gz"
      URL="https://nodejs.org/dist/${NODE_VERSION}/${TARBALL}"
      step "Downloading Node ${NODE_VERSION} (${PLAT}-${NARCH})…"
      mkdir -p "$NODE_DIR"; tmp="$(mktemp -d)"
      download "$URL" "$tmp/$TARBALL"
      tar -xzf "$tmp/$TARBALL" -C "$NODE_DIR" --strip-components=1
      rm -rf "$tmp"
    fi
    export PATH="$NODE_DIR/bin:$PATH"
    NPM="$NODE_DIR/bin/npm"
  fi
  step "Installing the Pear runtime…"
  "$NPM" install -g pear --prefix "$DIR/pear-cli" >/dev/null 2>&1 || "$NPM" install -g pear --prefix "$DIR/pear-cli"
  PEAR="$DIR/pear-cli/bin/pear"
  step "Bootstrapping Pear (one-time, ~30s)…"
  "$PEAR" --version >/dev/null 2>&1 || true
fi
[ -n "$PEAR" ] || { warn "Could not set up Pear. See the manual steps on $SITE."; exit 1; }

# fetch the Bearhole icon (best-effort — the launcher still works without it)
ICONS="$DIR/icons"; mkdir -p "$ICONS"
dl_icon () { download "$SITE/media/$1" "$ICONS/$1" 2>/dev/null || true; }

# ---- 3. create a launcher WITH the Bearhole icon ---------------------------
if [ "$PLAT" = darwin ]; then
  dl_icon bearhole.icns
  APP="$DIR/Bearhole.app"; MAC="$APP/Contents/MacOS"; RES="$APP/Contents/Resources"
  mkdir -p "$MAC" "$RES"
  [ -f "$ICONS/bearhole.icns" ] && cp "$ICONS/bearhole.icns" "$RES/bearhole.icns"
  cat > "$APP/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>CFBundleName</key><string>Bearhole</string>
  <key>CFBundleDisplayName</key><string>Bearhole</string>
  <key>CFBundleIdentifier</key><string>dk.bearhole.launcher</string>
  <key>CFBundleExecutable</key><string>bearhole</string>
  <key>CFBundleIconFile</key><string>bearhole</string>
  <key>CFBundlePackageType</key><string>APPL</string>
</dict></plist>
PLIST
  # PATH is BAKED at install time: Finder/launchd start apps with a minimal PATH
  # that lacks node (which pear's shebang needs), so a runtime $PATH would fail.
  # Common Homebrew/user bin dirs added as belt-and-suspenders; errors logged.
  cat > "$MAC/bearhole" <<LAUNCH
#!/bin/bash
export PATH="$DIR/node/bin:$DIR/pear-cli/bin:/opt/homebrew/bin:/usr/local/bin:\$HOME/.local/bin:$PATH"
exec "$PEAR" run "$LINK" >>"\${TMPDIR:-/tmp}/bearhole.log" 2>&1
LAUNCH
  chmod +x "$MAC/bearhole"
  step "Created ${BOLD}$APP${NC} (Bearhole icon shows in the Dock — the macOS icon workaround)."
  LAUNCH_HINT="Open ${BOLD}Bearhole${NC} from $DIR (or drag it into your Applications folder)."
  open "$APP" >/dev/null 2>&1 || true
else
  dl_icon bearhole.png
  APPS="$HOME/.local/share/applications"; ICONDIR="$HOME/.local/share/icons/hicolor/512x512/apps"
  mkdir -p "$APPS" "$ICONDIR"
  [ -f "$ICONS/bearhole.png" ] && cp "$ICONS/bearhole.png" "$ICONDIR/bearhole.png"
  # a run wrapper with the PATH baked at install time — the .desktop launcher runs
  # with a minimal session env that may lack node (which pear's shebang needs).
  RUN="$DIR/run-bearhole.sh"
  cat > "$RUN" <<RUNSH
#!/bin/bash
export PATH="$DIR/node/bin:$DIR/pear-cli/bin:$PATH"
exec "$PEAR" run "$LINK" >>"\${TMPDIR:-/tmp}/bearhole.log" 2>&1
RUNSH
  chmod +x "$RUN"
  cat > "$APPS/bearhole.desktop" <<DESK
[Desktop Entry]
Type=Application
Name=Bearhole
GenericName=P2P Community Workspace
Comment=Serverless, end-to-end-encrypted Discord alternative
Exec=$RUN
Icon=bearhole
Terminal=false
Categories=Network;InstantMessaging;Chat;
StartupNotify=true
# pear-electron runs every app through the shared pear-runtime-app binary, which
# reports WM_CLASS "pear-runtime-app" — bind it so the window groups under THIS
# launcher (Bearhole icon) in the taskbar. Remove if you run other Pear apps.
StartupWMClass=pear-runtime-app
DESK
  command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$APPS" 2>/dev/null || true
  command -v gtk-update-icon-cache >/dev/null 2>&1 && gtk-update-icon-cache -f "$HOME/.local/share/icons/hicolor" 2>/dev/null || true
  step "Created a ${BOLD}Bearhole${NC} launcher in your applications menu (with the Bearhole icon)."
  LAUNCH_HINT="Open ${BOLD}Bearhole${NC} from your applications menu."
fi

say ""
say "${TEAL}${BOLD}Done!${NC} $LAUNCH_HINT"
say "${DIM}First launch downloads the app peer-to-peer and may take a minute.${NC}"
say "${DIM}Uninstall: delete $DIR (and the Bearhole launcher).${NC}"
