#!/bin/sh
# ghaymah CLI installer
#
# Detects your OS and CPU architecture, downloads the matching binary,
# verifies its SHA-256 checksum against SHA256SUMS, and installs it.
#
# Usage:
#   curl -fsSL https://<your-host>/install.sh | sh
#   ./install.sh [--url <base>] [--version <v>] [--install-dir <dir>]
#
# Environment overrides:
#   GHAYMAH_BASE_URL     base URL hosting the binaries + SHA256SUMS
#   GHAYMAH_VERSION      optional version subdir (served as <base>/v<version>/)
#   GHAYMAH_INSTALL_DIR  install directory (default: ~/.local/bin, or /usr/local/bin as root)

set -eu

BASE_URL="${GHAYMAH_BASE_URL:-https://cli.ghaymah.app}"
INSTALL_DIR="${GHAYMAH_INSTALL_DIR:-}"
VERSION="${GHAYMAH_VERSION:-}"

err() { printf 'ghaymah-install: error: %s\n' "$1" >&2; shift; for m in "$@"; do printf '  %s\n' "$m" >&2; done; exit 1; }
info() { printf 'ghaymah-install: %s\n' "$*"; }
have() { command -v "$1" >/dev/null 2>&1; }

download() {
  url="$1"; dest="$2"
  if have curl; then
    curl -fsSL --retry 3 -o "$dest" "$url"
  elif have wget; then
    wget -q -O "$dest" "$url"
  else
    err "curl or wget is required to download ghaymah"
  fi
}

sha256() {
  if have sha256sum; then
    sha256sum "$1" | awk '{print $1}'
  elif have shasum; then
    shasum -a 256 "$1" | awk '{print $1}'
  else
    err "sha256sum or shasum is required to verify the download"
  fi
}

# ---- argument parsing ----
while [ "$#" -gt 0 ]; do
  case "$1" in
    --url)           BASE_URL="${2:?--url needs a value}"; shift 2 ;;
    --url=*)         BASE_URL="${1#--url=}"; shift ;;
    --version)       VERSION="${2:?--version needs a value}"; shift 2 ;;
    --version=*)     VERSION="${1#--version=}"; shift ;;
    --install-dir)   INSTALL_DIR="${2:?--install-dir needs a value}"; shift 2 ;;
    --install-dir=*) INSTALL_DIR="${1#--install-dir=}"; shift ;;
    -h|--help)
      cat <<'EOF'
Usage:
  curl -fsSL https://<your-host>/install.sh | sh
  ./install.sh [--url <base>] [--version <v>] [--install-dir <dir>]

Flags:
  --url <base>          base URL hosting the binaries + SHA256SUMS
  --version <v>         optional version subdir (served as <base>/v<version>/)
  --install-dir <dir>   install directory

Environment:
  GHAYMAH_BASE_URL      same as --url
  GHAYMAH_VERSION       same as --version
  GHAYMAH_INSTALL_DIR   same as --install-dir
EOF
      exit 0
      ;;
    *) err "unknown argument: $1 (try --help)" ;;
  esac
done

# ---- detect OS + architecture ----
os="$(uname -s)"
case "$os" in
  Linux)                   os=linux ;;
  Darwin)                  os=darwin ;;
  MSYS_NT*|MINGW*|CYGWIN*) os=windows ;;
  *) err "unsupported OS: $os (supported: Linux, macOS, Windows)" ;;
esac

arch="$(uname -m)"
case "$arch" in
  x86_64|amd64)  arch=amd64 ;;
  aarch64|arm64) arch=arm64 ;;
  *) err "unsupported CPU architecture: $arch (supported: amd64, arm64)" ;;
esac

file="ghaymah-${os}-${arch}"
[ "$os" = "windows" ] && file="${file}.exe"

# ---- install directory ----
if [ -z "$INSTALL_DIR" ]; then
  if [ "$(id -u 2>/dev/null || echo 0)" = "0" ]; then
    INSTALL_DIR="/usr/local/bin"
  else
    INSTALL_DIR="${HOME:-/tmp}/.local/bin"
  fi
fi
mkdir -p "$INSTALL_DIR"

# ---- download + verify ----
url_base="$BASE_URL"
[ -n "$VERSION" ] && url_base="${BASE_URL%/}/v${VERSION}"

info "detected ${os}/${arch}"
info "downloading ${file} from ${url_base}"

tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT HUP INT TERM

download "${url_base}/${file}" "${tmpdir}/${file}"
download "${url_base}/SHA256SUMS" "${tmpdir}/SHA256SUMS"

expected="$(awk -v f="$file" '$2 == f { print $1 }' "${tmpdir}/SHA256SUMS")"
[ -n "$expected" ] || err "${file} not found in SHA256SUMS" "is the base URL correct? (${url_base})"

actual="$(sha256 "${tmpdir}/${file}")"
if [ "$expected" != "$actual" ]; then
  err "checksum mismatch for ${file}" "expected ${expected}" "got      ${actual}"
fi
info "checksum verified"

# ---- install ----
if [ "$os" = "windows" ]; then
  target="${INSTALL_DIR}/ghaymah.exe"
else
  target="${INSTALL_DIR}/ghaymah"
fi

[ "$os" = "windows" ] && rm -f "$target"
cp "${tmpdir}/${file}" "$target"
chmod 0755 "$target"

info "installed: ${target}"

# ---- PATH hint ----
case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *)
    info "note: ${INSTALL_DIR} is not on your PATH"
    info "add it with:  export PATH=\"\$PATH:${INSTALL_DIR}\""
    ;;
esac

info "run 'ghaymah --help' to get started"
