#!/bin/sh
# Heddle installer — https://heddle.sh/install.sh
#
#   curl -fsSL https://heddle.sh/install.sh | sh
#
# Downloads the latest signed release binary from GitHub, verifies its
# SHA-256, and installs `heddle` onto your PATH. POSIX sh, no deps beyond
# curl (or wget), tar, and a sha256 tool.
#
# Knobs (env vars):
#   HEDDLE_VERSION       pin a tag, e.g. v0.3.0 (default: latest release)
#   HEDDLE_INSTALL_DIR   install location (default: ~/.local/bin)
#
# On macOS the recommended path is Homebrew:
#   brew install --cask HeddleCo/tap/heddle
# This script still works there, but Homebrew handles upgrades for you.

set -eu

REPO="HeddleCo/heddle"
BINARY="heddle"

info() { printf '\033[1;32m==>\033[0m %s\n' "$1"; }
warn() { printf '\033[1;33mwarning:\033[0m %s\n' "$1" >&2; }
err() { printf '\033[1;31merror:\033[0m %s\n' "$1" >&2; exit 1; }

# ── download helper (curl or wget) ──────────────────────────────────
if command -v curl >/dev/null 2>&1; then
  dl() { curl -fsSL "$1" -o "$2"; }
  dl_stdout() { curl -fsSL "$1"; }
elif command -v wget >/dev/null 2>&1; then
  dl() { wget -qO "$2" "$1"; }
  dl_stdout() { wget -qO - "$1"; }
else
  err "need curl or wget on PATH"
fi

# ── detect platform ─────────────────────────────────────────────────
os="$(uname -s)"
arch="$(uname -m)"

case "$os" in
  Linux) os_part="unknown-linux-gnu" ;;
  Darwin)
    os_part="apple-darwin"
    warn "on macOS the recommended install is: brew install --cask HeddleCo/tap/heddle"
    ;;
  *) err "unsupported OS '$os'. See https://github.com/$REPO/releases" ;;
esac

case "$arch" in
  x86_64 | amd64) arch_part="x86_64" ;;
  aarch64 | arm64) arch_part="aarch64" ;;
  *) err "unsupported architecture '$arch'. See https://github.com/$REPO/releases" ;;
esac

target="${arch_part}-${os_part}"

# ── resolve version ─────────────────────────────────────────────────
tag="${HEDDLE_VERSION:-}"
if [ -z "$tag" ]; then
  info "Resolving the latest release..."
  tag="$(dl_stdout "https://api.github.com/repos/$REPO/releases/latest" \
    | grep '"tag_name"' \
    | head -n 1 \
    | sed 's/.*"tag_name":[[:space:]]*"\([^"]*\)".*/\1/')"
  [ -n "$tag" ] || err "could not determine the latest release tag"
fi

asset="${BINARY}-${tag}-${target}.tar.gz"
base="https://github.com/$REPO/releases/download/${tag}/${asset}"

# ── download + verify ───────────────────────────────────────────────
tmp="$(mktemp -d 2>/dev/null || mktemp -d -t heddle)"
trap 'rm -rf "$tmp"' EXIT INT TERM

info "Downloading ${BINARY} ${tag} (${target})..."
dl "$base" "$tmp/$asset" || err "download failed: $base"

if dl "$base.sha256" "$tmp/$asset.sha256" 2>/dev/null; then
  expected="$(awk '{print $1}' "$tmp/$asset.sha256")"
  if command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "$tmp/$asset" | awk '{print $1}')"
  elif command -v shasum >/dev/null 2>&1; then
    actual="$(shasum -a 256 "$tmp/$asset" | awk '{print $1}')"
  else
    actual=""
    warn "no sha256 tool found; skipping checksum verification"
  fi
  if [ -n "$actual" ]; then
    [ "$actual" = "$expected" ] || err "checksum mismatch (expected $expected, got $actual)"
    info "Checksum verified."
  fi
else
  warn "no checksum published for $asset; skipping verification"
fi

# ── extract + install ───────────────────────────────────────────────
tar -xzf "$tmp/$asset" -C "$tmp" || err "failed to extract $asset"
bin_src="$(find "$tmp" -type f -name "$BINARY" -perm -u+x 2>/dev/null | head -n 1)"
[ -n "$bin_src" ] || bin_src="$(find "$tmp" -type f -name "$BINARY" 2>/dev/null | head -n 1)"
[ -n "$bin_src" ] || err "could not find the '$BINARY' binary in $asset"

install_dir="${HEDDLE_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$install_dir" || err "could not create $install_dir"
install -m 0755 "$bin_src" "$install_dir/$BINARY" 2>/dev/null \
  || { cp "$bin_src" "$install_dir/$BINARY" && chmod 0755 "$install_dir/$BINARY"; } \
  || err "could not write to $install_dir"

info "Installed $BINARY to $install_dir/$BINARY"

# ── PATH hint ───────────────────────────────────────────────────────
case ":$PATH:" in
  *":$install_dir:"*) ;;
  *)
    warn "$install_dir is not on your PATH."
    printf '       Add it to your shell profile:\n\n         export PATH="%s:$PATH"\n\n' "$install_dir"
    ;;
esac

info "Done. Run: $BINARY version"
