#!/bin/sh
set -eu

BASE_URL="${HANDOVER_URL:-https://handover.sh}"
INSTALL_DIR="${HANDOVER_INSTALL_DIR:-$HOME/.local/bin}"
TARGET="$INSTALL_DIR/handover"
TEMP="${TMPDIR:-/tmp}/handover-install-$$"

cleanup() {
  rm -f "$TEMP"
}
trap cleanup EXIT INT TERM

if ! command -v node >/dev/null 2>&1; then
  printf '%s\n' "Handover requires Node.js 22.13 or newer." >&2
  printf '%s\n' "Install Node.js, then run this installer again." >&2
  exit 1
fi

NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
NODE_MINOR="$(node -p 'process.versions.node.split(".")[1]')"
if [ "$NODE_MAJOR" -lt 22 ] || { [ "$NODE_MAJOR" -eq 22 ] && [ "$NODE_MINOR" -lt 13 ]; }; then
  printf '%s\n' "Handover requires Node.js 22.13 or newer; found $(node --version)." >&2
  exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
  printf '%s\n' "curl is required to download the Handover command." >&2
  exit 1
fi

mkdir -p "$INSTALL_DIR"
curl -fsSL "$BASE_URL/handover.mjs" -o "$TEMP"

if ! head -n 1 "$TEMP" | grep -q '^#!/usr/bin/env node'; then
  printf '%s\n' "The downloaded file did not look like the Handover command." >&2
  exit 1
fi

chmod 0755 "$TEMP"
mv "$TEMP" "$TARGET"
trap - EXIT INT TERM

printf '%s\n' "Installed Handover to $TARGET"
case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *)
    printf '%s\n' "Add $INSTALL_DIR to PATH, then restart your shell."
    printf '%s\n' "For zsh:  echo 'export PATH=\"$INSTALL_DIR:\$PATH\"' >> ~/.zshrc"
    ;;
esac
printf '%s\n' "Next: handover --help"
