#!/bin/sh
# Install Chorong prebuilt binaries from GitHub Releases.
#
# Usage:
#   curl -fsSL https://chorong.sh/install.sh | sh
#   curl -fsSL https://chorong.sh/install.sh | sh -s -- decide factory
#   curl -fsSL https://chorong.sh/install.sh | sh -s -- --version v0.1.1 --dir ~/.local/bin decide
#
# Environment variables:
#   VERSION      Release tag to install (default: latest release)
#   INSTALL_DIR  Destination directory (default: $HOME/.local/bin)
set -eu

REPO="chorong-sh/chorong"
VERSION="${VERSION:-}"
INSTALL_DIR="${INSTALL_DIR:-${HOME}/.local/bin}"

usage() {
  cat <<'EOF'
Install Chorong prebuilt binaries from GitHub Releases.

Usage:
  install.sh [options] [tool ...]

Options:
  -v, --version TAG   Install a specific release tag (e.g. v0.1.1)
  -d, --dir DIR       Install binaries into DIR (default: ~/.local/bin)
  -h, --help          Show this help message

Tools:
  chorong (default, full suite), factory, decide, agentbus, prsync,
  orgctl, gh-nudge, gh-ask, docsync, genfiles
EOF
}

die() {
  printf 'chorong install: %s\n' "$1" >&2
  exit 1
}

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    die "required command not found: $1"
  fi
}

detect_os() {
  os_raw=$(uname -s)
  case "$os_raw" in
    Darwin) printf 'darwin' ;;
    Linux) printf 'linux' ;;
    *) die "unsupported OS: $os_raw (expected Darwin or Linux)" ;;
  esac
}

detect_arch() {
  arch_raw=$(uname -m)
  case "$arch_raw" in
    x86_64 | amd64) printf 'amd64' ;;
    arm64 | aarch64) printf 'arm64' ;;
    *) die "unsupported architecture: $arch_raw (expected amd64 or arm64)" ;;
  esac
}

validate_tool() {
  case "$1" in
    chorong | factory | decide | agentbus | prsync | orgctl | gh-nudge | gh-ask | docsync | genfiles)
      return 0
      ;;
    *)
      die "unknown tool: $1 (expected chorong, factory, decide, agentbus, prsync, orgctl, gh-nudge, gh-ask, docsync, or genfiles)"
      ;;
  esac
}

resolve_version() {
  if [ -n "$VERSION" ]; then
    case "$VERSION" in
      v*) printf '%s' "$VERSION" ;;
      *) printf 'v%s' "$VERSION" ;;
    esac
    return 0
  fi

  effective_url=$(curl -fsSLI -o /dev/null -w '%{url_effective}' "https://github.com/${REPO}/releases/latest")
  tag=${effective_url##*/}
  case "$tag" in
    v[0-9]*)
      printf '%s' "$tag"
      ;;
    *)
      die "could not determine latest release tag from ${effective_url}"
      ;;
  esac
}

sha256_file() {
  file_path=$1
  out_path=$2
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file_path" >"$out_path"
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file_path" >"$out_path"
  else
    die "required command not found: sha256sum or shasum"
  fi
  read -r computed_hash _ <"$out_path"
  printf '%s' "$computed_hash"
}

tools=""
while [ $# -gt 0 ]; do
  case "$1" in
    -v | --version)
      [ $# -ge 2 ] || die "$1 requires a value"
      VERSION=$2
      shift 2
      ;;
    -d | --dir)
      [ $# -ge 2 ] || die "$1 requires a value"
      INSTALL_DIR=$2
      shift 2
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    --)
      shift
      while [ $# -gt 0 ]; do
        validate_tool "$1"
        tools="${tools}${tools:+ }$1"
        shift
      done
      ;;
    -*)
      die "unknown option: $1 (run with --help)"
      ;;
    *)
      validate_tool "$1"
      tools="${tools}${tools:+ }$1"
      shift
      ;;
  esac
done

if [ -z "$tools" ]; then
  tools="chorong"
fi

require_cmd curl
require_cmd tar
require_cmd awk
require_cmd uname

os=$(detect_os)
arch=$(detect_arch)
tag=$(resolve_version)
ver=${tag#v}
base_url="https://github.com/${REPO}/releases/download/${tag}"

tmpdir=$(mktemp -d)
cleanup() {
  rm -rf "$tmpdir"
}
trap cleanup EXIT INT TERM

checksums_file="${tmpdir}/checksums.txt"
printf 'Downloading Chorong %s (%s/%s)...\n' "$tag" "$os" "$arch" >&2
curl -fsSL -o "$checksums_file" "${base_url}/checksums.txt"

mkdir -p "$INSTALL_DIR"
installed=""

for tool in $tools; do
  archive="${tool}_${ver}_${os}_${arch}.tar.gz"
  archive_path="${tmpdir}/${archive}"
  extract_dir="${tmpdir}/extract_${tool}"

  curl -fsSL -o "$archive_path" "${base_url}/${archive}"

  expected_hash=$(awk -v target="$archive" '$2 == target { print $1; exit }' "$checksums_file")
  if [ -z "$expected_hash" ]; then
    die "checksum entry not found for ${archive}"
  fi

  actual_hash=$(sha256_file "$archive_path" "${tmpdir}/sha_${tool}")
  if [ "$actual_hash" != "$expected_hash" ]; then
    die "checksum mismatch for ${archive}: expected ${expected_hash}, got ${actual_hash}"
  fi

  mkdir -p "$extract_dir"
  # Skip nested paths (e.g. <tool>/README.md) so they cannot collide with the
  # top-level binary of the same name.
  tar --exclude='*/*' -xzf "$archive_path" -C "$extract_dir"

  for entry in "${extract_dir}"/*; do
    [ -f "$entry" ] || continue
    name=${entry##*/}
    case "$name" in
      LICENSE | *.md) continue ;;
    esac
    if [ -x "$entry" ]; then
      cp "$entry" "${INSTALL_DIR}/${name}"
      chmod 0755 "${INSTALL_DIR}/${name}"
      installed="${installed}${installed:+ }${name}"
    fi
  done
done

printf 'Installed to %s: %s\n' "$INSTALL_DIR" "$installed" >&2

case ":${PATH:-}:" in
  *":${INSTALL_DIR}:"*) ;;
  *)
    printf "Note: %s is not in your PATH. Add it with:\n  export PATH=\"%s:\$PATH\"\n" "$INSTALL_DIR" "$INSTALL_DIR" >&2
    ;;
esac
