#!/bin/sh
# Install the prebuilt `instinct` binary from a GitHub release. No Rust needed.
#
#   curl -fsSLO https://raw.githubusercontent.com/koscak-labs/instinct/main/install.sh
#   sh install.sh
#
# Environment:
#   INSTINCT_VERSION      release tag such as v0.3.0 (default: the latest release)
#   INSTINCT_INSTALL_DIR  where to put the binary (default: $HOME/.local/bin)
#   INSTINCT_RELEASE_BASE for tests only: a directory or file:// URL holding the release assets
#
# The script downloads the archive and SHA256SUMS, refuses to install unless the checksum
# matches, and writes only to the install dir and a temp dir that is removed on exit.
# It never uses sudo and never edits shell startup files.
set -eu

REPO=koscak-labs/instinct

say() { printf '%s\n' "$*"; }
die() { printf 'install.sh: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }
fallback() { say "Fallback with Rust 1.89 or later: cargo install --locked instinct-cli" >&2; }

# --- target triple ---------------------------------------------------------
os=$(uname -s)
arch=$(uname -m)
case $os in
  Linux) os_part=unknown-linux-gnu ;;
  Darwin) os_part=apple-darwin ;;
  *) printf 'install.sh: unsupported operating system: %s\n' "$os" >&2; fallback; exit 1 ;;
esac
case $arch in
  x86_64 | amd64) arch_part=x86_64 ;;
  aarch64 | arm64) arch_part=aarch64 ;;
  *) printf 'install.sh: unsupported CPU architecture: %s\n' "$arch" >&2; fallback; exit 1 ;;
esac
target=$arch_part-$os_part

# --- downloader ------------------------------------------------------------
# fetch SOURCE DEST: SOURCE is an https URL, a file:// URL or a plain path.
fetch() {
  case $1 in
    file://*) cp "${1#file://}" "$2" ;;
    http://* | https://*)
      if have curl; then
        curl -fsSL "$1" -o "$2"
      elif have wget; then
        wget -q -O "$2" "$1"
      else
        die "need curl or wget to download $1"
      fi ;;
    *) cp "$1" "$2" ;;
  esac
}

tmp=$(mktemp -d "${TMPDIR:-/tmp}/instinct-install.XXXXXX") || die "cannot create a temp dir"
trap 'rm -rf "$tmp"' EXIT
trap 'exit 1' INT TERM HUP

# --- release tag -----------------------------------------------------------
tag=${INSTINCT_VERSION:-}
if [ -z "$tag" ]; then
  [ -z "${INSTINCT_RELEASE_BASE:-}" ] || die "set INSTINCT_VERSION when INSTINCT_RELEASE_BASE is used"
  fetch "https://api.github.com/repos/$REPO/releases/latest" "$tmp/latest.json" \
    || die "could not read the latest release from GitHub"
  tag=$(sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$tmp/latest.json" | head -n 1)
  [ -n "$tag" ] || die "the GitHub API reply had no tag_name; set INSTINCT_VERSION=v0.3.0"
fi
case $tag in v*) ;; *) tag=v$tag ;; esac

base=${INSTINCT_RELEASE_BASE:-https://github.com/$REPO/releases/download/$tag}
asset=instinct-cli-$target-$tag.tgz
say "Installing instinct $tag for $target"

# --- download and verify ---------------------------------------------------
fetch "$base/$asset" "$tmp/$asset" || die "could not download $asset from $base (does $tag ship $target?)"
fetch "$base/SHA256SUMS" "$tmp/SHA256SUMS" || die "could not download SHA256SUMS from $base"

expected=$(awk -v name="$asset" '$2 == name || $2 == "*" name { print $1; exit }' "$tmp/SHA256SUMS")
[ -n "$expected" ] || die "SHA256SUMS has no line for $asset; refusing to install"

if have sha256sum; then
  actual=$(sha256sum "$tmp/$asset" | awk '{ print $1 }')
elif have shasum; then
  actual=$(shasum -a 256 "$tmp/$asset" | awk '{ print $1 }')
else
  die "need sha256sum or shasum to verify the download"
fi
[ "$actual" = "$expected" ] || die "checksum mismatch for $asset (expected $expected, got $actual); refusing to install"
say "Checksum OK ($actual)"

# --- install ---------------------------------------------------------------
mkdir "$tmp/unpack"
tar -xzf "$tmp/$asset" -C "$tmp/unpack" instinct || die "the archive has no instinct binary"

dir=${INSTINCT_INSTALL_DIR:-$HOME/.local/bin}
mkdir -p "$dir" || die "cannot create $dir"
cp "$tmp/unpack/instinct" "$dir/.instinct.new"
chmod 755 "$dir/.instinct.new"
mv -f "$dir/.instinct.new" "$dir/instinct"
say "Installed $dir/instinct"

case ":$PATH:" in
  *":$dir:"*) say "$dir is on your PATH." ;;
  *)
    say "$dir is not on your PATH. To add it for this shell:"
    say "  export PATH=\"$dir:\$PATH\""
    say "Add that line to your shell profile to keep it. This script does not edit it." ;;
esac

say "Next: instinct starter --apply"
