#!/bin/sh
#
# install.sh — one-line installer for guestclawcli.
#
# Customer-facing entry point. Hosted at https://install.guestclaw.ai so users
# can run:
#
#     curl -fsSL https://install.guestclaw.ai | sh
#
# Behavior:
#   1. Detects OS + arch and maps to one of:
#        darwin-arm64 | darwin-x64 | linux-x64 | linux-arm64
#   2. Resolves the latest release tag from GitHub (or honours $GUESTCLAW_VERSION).
#   3. Downloads guestclaw-<asset_suffix> from the corresponding release into
#      ~/.guestclaw/bin/guestclaw via curl (no Gatekeeper quarantine on macOS).
#   4. chmod +x, then suggests the right PATH export for the user's shell.
#
# POSIX /bin/sh only. No bashisms. set -eu (no pipefail — not POSIX).

set -eu

REPO_OWNER="${GUESTCLAW_REPO_OWNER:-andthezhang}"
REPO_NAME="${GUESTCLAW_REPO_NAME:-guestclaw-craft}"
INSTALL_DIR="${GUESTCLAW_INSTALL_DIR:-${HOME}/.guestclaw/bin}"
BIN_NAME="guestclaw"
DOCS_URL="https://github.com/${REPO_OWNER}/${REPO_NAME}#install"

log() { printf '%s\n' "$*"; }
err() { printf 'error: %s\n' "$*" >&2; }

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    err "required command '$1' not found in PATH."
    exit 127
  fi
}

require_cmd curl
require_cmd uname
require_cmd chmod
require_cmd mkdir

# --- 1. detect platform ---------------------------------------------------

uname_s="$(uname -s)"
uname_m="$(uname -m)"

case "${uname_s}" in
  Darwin) os="darwin" ;;
  Linux)  os="linux" ;;
  *)
    err "unsupported OS: ${uname_s}. See ${DOCS_URL}"
    exit 65
    ;;
esac

case "${uname_m}" in
  arm64|aarch64) arch="arm64" ;;
  x86_64|amd64)  arch="x64" ;;
  *)
    err "unsupported arch: ${uname_m}. See ${DOCS_URL}"
    exit 65
    ;;
esac

asset_suffix="${os}-${arch}"

case "${asset_suffix}" in
  darwin-arm64|darwin-x64|linux-x64|linux-arm64) ;;
  *)
    err "no release artifact for platform '${asset_suffix}'. See ${DOCS_URL}"
    exit 65
    ;;
esac

# --- 2. resolve version ---------------------------------------------------

if [ -n "${GUESTCLAW_VERSION:-}" ]; then
  tag="${GUESTCLAW_VERSION}"
  log "Using pinned version: ${tag}"
else
  log "Resolving latest release of ${REPO_OWNER}/${REPO_NAME}..."
  # Grep the tag_name field out of the API response. No jq dependency.
  api_url="https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/releases/latest"
  release_json="$(curl -fsSL "${api_url}" 2>/dev/null || true)"
  if [ -z "${release_json}" ]; then
    err "could not fetch release metadata from ${api_url}"
    err "set GUESTCLAW_VERSION=v0.x.y to pin a version, or check your network."
    exit 69
  fi
  tag="$(printf '%s' "${release_json}" | grep -o '"tag_name"[^,]*' | head -n1 | sed -e 's/.*"tag_name"[^"]*"\([^"]*\)".*/\1/')"
  if [ -z "${tag}" ]; then
    err "could not parse tag_name from GitHub API response."
    exit 69
  fi
  log "Latest release: ${tag}"
fi

# --- 3. download ----------------------------------------------------------

download_url="https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/download/${tag}/guestclaw-${asset_suffix}"
target_path="${INSTALL_DIR}/${BIN_NAME}"

log "Downloading ${download_url}"
mkdir -p "${INSTALL_DIR}"

# Download to a tmp file, then atomically move into place.
tmp_path="${target_path}.tmp.$$"
if ! curl -fsSL --retry 3 --retry-delay 2 -o "${tmp_path}" "${download_url}"; then
  err "download failed: ${download_url}"
  err "If this release doesn't have a ${asset_suffix} artifact, see ${DOCS_URL}"
  rm -f "${tmp_path}"
  exit 69
fi

mv "${tmp_path}" "${target_path}"
chmod +x "${target_path}"

log "Installed: ${target_path}"

# --- 4. PATH hint ---------------------------------------------------------

# Detect whether INSTALL_DIR is already on PATH.
case ":${PATH}:" in
  *":${INSTALL_DIR}:"*) on_path=1 ;;
  *) on_path=0 ;;
esac

if [ "${on_path}" -eq 0 ]; then
  shell_name="$(basename "${SHELL:-/bin/sh}")"
  case "${shell_name}" in
    zsh)  rc_file="\${HOME}/.zshrc" ;;
    bash)
      if [ "${os}" = "darwin" ]; then
        rc_file="\${HOME}/.bash_profile"
      else
        rc_file="\${HOME}/.bashrc"
      fi
      ;;
    fish) rc_file="\${HOME}/.config/fish/config.fish" ;;
    *)    rc_file="\${HOME}/.profile" ;;
  esac

  printf '\n'
  log "${INSTALL_DIR} is NOT on your PATH. Add it with:"
  printf '\n'
  if [ "${shell_name}" = "fish" ]; then
    log "    echo 'set -gx PATH ${INSTALL_DIR} \$PATH' >> ${rc_file}"
  else
    log "    echo 'export PATH=\"${INSTALL_DIR}:\$PATH\"' >> ${rc_file}"
  fi
  printf '\n'
  log "Then restart your shell or run: source ${rc_file}"
else
  log "${INSTALL_DIR} is already on your PATH."
fi

# --- 5. next steps --------------------------------------------------------

printf '\n'
log "Next steps:"
log "    ${BIN_NAME} init"
log "    ${BIN_NAME} status"
printf '\n'
log "Docs: ${DOCS_URL}"
