#!/bin/sh
# Chronary CLI installer.
#
# Usage:
#   curl -sSfL https://chronary.ai/install.sh | sh
#   curl -sSfL https://chronary.ai/install.sh | sh -s -- --version 0.1.1
#   curl -sSfL https://chronary.ai/install.sh | sh -s -- --prefix "$HOME/.local"
#
# Environment:
#   CHRONARY_VERSION    Override the version (defaults to latest release).
#   CHRONARY_PREFIX     Install prefix (defaults to /usr/local).
#   CHRONARY_REPO       Override the source repo (Chronary/chronary-cli).

set -eu

CHRONARY_VERSION="${CHRONARY_VERSION:-latest}"
CHRONARY_PREFIX="${CHRONARY_PREFIX:-/usr/local}"
CHRONARY_REPO="${CHRONARY_REPO:-Chronary/chronary-cli}"

while [ $# -gt 0 ]; do
  case "$1" in
    --version) CHRONARY_VERSION="$2"; shift 2 ;;
    --prefix) CHRONARY_PREFIX="$2"; shift 2 ;;
    -h|--help)
      sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'
      exit 0
      ;;
    *) printf 'Unknown flag: %s\n' "$1" >&2; exit 1 ;;
  esac
done

log() {
  printf '==> %s\n' "$*"
}

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

# Detect OS.
os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in
  linux|darwin) ;;
  *) err "Unsupported OS: $os. Download a binary from https://github.com/${CHRONARY_REPO}/releases" ;;
esac

# Detect architecture.
arch=$(uname -m)
case "$arch" in
  x86_64|amd64) arch="amd64" ;;
  arm64|aarch64) arch="arm64" ;;
  *) err "Unsupported architecture: $arch" ;;
esac

# Pick a sha256 tool that exists on the platform (sha256sum on Linux, shasum on macOS).
if command -v sha256sum >/dev/null 2>&1; then
  sha256_cmd="sha256sum"
elif command -v shasum >/dev/null 2>&1; then
  sha256_cmd="shasum -a 256"
else
  err "Need sha256sum or shasum to verify checksums"
fi

# Resolve version.
if [ "$CHRONARY_VERSION" = "latest" ]; then
  log "Resolving latest version of $CHRONARY_REPO..."
  CHRONARY_VERSION=$(
    curl -sSfL "https://api.github.com/repos/${CHRONARY_REPO}/releases/latest" \
      | grep '"tag_name":' \
      | head -n1 \
      | sed -E 's/.*"v?([^"]+)".*/\1/'
  )
  if [ -z "$CHRONARY_VERSION" ]; then
    err "Could not resolve latest version. Pass --version X.Y.Z explicitly."
  fi
fi
version="${CHRONARY_VERSION#v}"

archive="chronary_${version}_${os}_${arch}.tar.gz"
base_url="https://github.com/${CHRONARY_REPO}/releases/download/v${version}"
archive_url="${base_url}/${archive}"
checksums_url="${base_url}/sha256sums.txt"

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

log "Downloading ${archive}..."
curl -sSfL "$archive_url" -o "$tmpdir/$archive" \
  || err "Download failed: $archive_url"

log "Verifying checksum..."
curl -sSfL "$checksums_url" -o "$tmpdir/sha256sums.txt" \
  || err "Could not download sha256sums.txt from $checksums_url"

expected=$(grep " ${archive}\$" "$tmpdir/sha256sums.txt" | awk '{print $1}')
[ -n "$expected" ] || err "No checksum entry for $archive in sha256sums.txt"

actual=$($sha256_cmd "$tmpdir/$archive" | awk '{print $1}')
[ "$actual" = "$expected" ] \
  || err "Checksum mismatch (expected $expected, got $actual)"

log "Extracting..."
tar -xzf "$tmpdir/$archive" -C "$tmpdir"

target_dir="${CHRONARY_PREFIX}/bin"
target_bin="${target_dir}/chronary"

mkdir -p "$target_dir" 2>/dev/null || true

if [ -w "$target_dir" ]; then
  mv "$tmpdir/chronary" "$target_bin"
  chmod +x "$target_bin"
else
  log "Installing to $target_bin (requires sudo for $target_dir)..."
  sudo mv "$tmpdir/chronary" "$target_bin"
  sudo chmod +x "$target_bin"
fi

log "Installed chronary $version to $target_bin"

if command -v chronary >/dev/null 2>&1 && [ "$(command -v chronary)" = "$target_bin" ]; then
  chronary --version
else
  cat <<MSG
Note: $target_dir is not on your PATH. Add it with one of:
  echo 'export PATH="$target_dir:\$PATH"' >> ~/.bashrc
  echo 'export PATH="$target_dir:\$PATH"' >> ~/.zshrc
  # or run directly: $target_bin --version
MSG
fi
