#!/bin/sh
# Install a release binary of `triage` on Linux x86_64.
#
#   curl -fsSL https://raw.githubusercontent.com/0xTanzim/triage/main/install.sh | sh
#
# Environment overrides:
#   TRIAGE_VERSION       release tag to install (default: latest complete release), e.g. v1.0.0
#   TRIAGE_INSTALL_DIR   target directory (default: ~/.local/bin)
#   TRIAGE_INSTALL_NAME  binary file name (default: triage)
#   TRIAGE_VARIANT       auto | musl | gnu (default: auto; musl static everywhere,
#                        or gnu when /dev/nvidiactl is present with fallback to musl)
#   TRIAGE_RELEASES_URL  releases base URL (default: https://github.com/0xTanzim/triage/releases)
#   TRIAGE_DOWNLOAD_URL  direct asset directory URL (mirrors / local testing)
set -eu

fail() {
  printf 'triage install: %s\n' "$*" >&2
  exit 1
}

usage() {
  cat <<'EOF'
Usage: install.sh [options]

Options:
  -v, --version <tag>   Release tag to install (default: latest)
  -d, --dir <path>      Install directory (default: ~/.local/bin)
  -n, --name <name>     Installed binary name (default: triage)
      --musl            Force static musl binary (works on any Linux x86_64 distro)
      --gnu             Prefer glibc binary (for runtime NVML GPU telemetry)
      --dry-run         Resolve release and print what would be installed
  -h, --help            Show this help
EOF
}

# Reject plain HTTP except explicit loopback addresses, and reject @ authority
# tricks like http://127.0.0.1@evil.example/.
check_source() {
  case "$2" in
    https://*) scheme=https authority=${2#https://} ;;
    http://*)  scheme=http  authority=${2#http://} ;;
    *) fail "$1 must use https (or http to localhost): $2" ;;
  esac
  authority=${authority%%/*}
  authority=${authority%%\?*}
  authority=${authority%%#*}
  case "$authority" in
    *@*) fail "$1 must use https (or http to localhost): $2" ;;
  esac
  [ "$scheme" = https ] && return 0
  host=$authority
  case "$authority" in
    "[::1]:"* | localhost:* | 127.0.0.1:*)
      host=${authority%:*}
      case "${authority##*:}" in "" | *[!0-9]*) fail "$1 has an invalid port: $2" ;; esac
      ;;
  esac
  case "$host" in
    localhost | 127.0.0.1 | "[::1]") return 0 ;;
    *) fail "$1 must use https (or http to localhost): $2" ;;
  esac
}

compute_sha256() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{ print $1 }'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{ print $1 }'
  else
    fail "sha256sum or shasum is required to verify the download"
  fi
}

# Keep every action inside main() so a truncated curl stream runs nothing.
main() {
  version="${TRIAGE_VERSION:-latest}"
  dir="${TRIAGE_INSTALL_DIR:-}"
  name="${TRIAGE_INSTALL_NAME:-triage}"
  variant="${TRIAGE_VARIANT:-auto}"
  dry_run=0

  while [ "$#" -gt 0 ]; do
    case "$1" in
      -v | --version)
        [ "$#" -ge 2 ] || fail "$1 requires a value"
        version="$2"
        shift 2
        ;;
      -d | --dir)
        [ "$#" -ge 2 ] || fail "$1 requires a value"
        dir="$2"
        shift 2
        ;;
      -n | --name)
        [ "$#" -ge 2 ] || fail "$1 requires a value"
        name="$2"
        shift 2
        ;;
      --musl)
        variant="musl"
        shift
        ;;
      --gnu)
        variant="gnu"
        shift
        ;;
      --dry-run)
        dry_run=1
        shift
        ;;
      -h | --help)
        usage
        exit 0
        ;;
      *)
        fail "unknown option: $1 (run with --help)"
        ;;
    esac
  done

  os=$(uname -s)
  arch=$(uname -m)
  [ "$os" = "Linux" ] || fail "unsupported OS '$os'; triage supports Linux x86_64"
  case "$arch" in
    x86_64 | amd64) arch="x86_64" ;;
    *) fail "unsupported architecture '$arch'; prebuilt binaries target Linux x86_64 (build from source with cmake)" ;;
  esac

  case "$variant" in
    auto | musl | gnu) ;;
    *) fail "invalid variant '$variant'; use auto, musl, or gnu" ;;
  esac

  case "$version" in
    latest | v*) ;;
    *) version="v$version" ;;
  esac

  releases="${TRIAGE_RELEASES_URL:-https://github.com/0xTanzim/triage/releases}"
  releases=${releases%/}
  check_source TRIAGE_RELEASES_URL "$releases"
  if [ -n "${TRIAGE_DOWNLOAD_URL:-}" ]; then
    check_source TRIAGE_DOWNLOAD_URL "$TRIAGE_DOWNLOAD_URL"
  fi

  if [ -z "$dir" ]; then
    if [ -n "${HOME:-}" ]; then
      dir="$HOME/.local/bin"
    else
      fail "HOME is not set; pass --dir or set TRIAGE_INSTALL_DIR"
    fi
  fi

  download() {
    if command -v curl >/dev/null 2>&1; then
      curl -fsSL --retry 3 -o "$2" "$1"
    elif command -v wget >/dev/null 2>&1; then
      wget -q -O "$2" "$1"
    else
      fail "curl or wget is required"
    fi
  }

  fetch() {
    if command -v curl >/dev/null 2>&1; then
      curl -fsSL --retry 3 "$1"
    elif command -v wget >/dev/null 2>&1; then
      wget -q -O - "$1"
    else
      fail "curl or wget is required"
    fi
  }

  # Pick variant order: gnu runs NVML dlopen on compatible glibc hosts;
  # musl is static-pie and runs on any Linux x86_64 host.
  try_variants="musl"
  if [ "$variant" = "gnu" ]; then
    try_variants="gnu"
  elif [ "$variant" = "auto" ] && [ -e /dev/nvidiactl ] && getconf GNU_LIBC_VERSION >/dev/null 2>&1; then
    try_variants="gnu musl"
  fi

  if [ "$dry_run" -eq 1 ]; then
    printf 'Target: Linux %s | Version: %s | Variants: %s | Dir: %s/%s\n' \
      "$arch" "$version" "$try_variants" "$dir" "$name"
    exit 0
  fi

  # Stage inside the destination directory so /tmp noexec cannot break --version
  # checks and the final mv is atomic on the same filesystem.
  mkdir -p "$dir" || fail "cannot create directory $dir"
  dir=$(cd "$dir" && pwd) || fail "cannot access directory $dir"
  tmp=$(mktemp -d "$dir/.triage-install.XXXXXX") || fail "cannot write to $dir"
  trap 'rm -rf "$tmp"' EXIT

  if [ -n "${TRIAGE_DOWNLOAD_URL:-}" ]; then
    base=${TRIAGE_DOWNLOAD_URL%/}
  elif [ "$version" != "latest" ]; then
    base="$releases/download/$version"
  else
    # Only pick a release tag once its SHA256SUMS file is uploaded.
    newest=""
    tags=$(fetch "$releases.atom" 2>/dev/null |
      grep -o '/releases/tag/v[0-9]*\.[0-9]*\.[0-9]*"' | sed 's#.*/tag/##; s/"$//' | awk '!seen[$0]++') || tags=""
    for tag in $tags; do
      [ -n "$newest" ] || newest=$tag
      if download "$releases/download/$tag/SHA256SUMS" "$tmp/SHA256SUMS" 2>/dev/null; then
        version=$tag
        break
      fi
    done
    [ "$version" != "latest" ] || fail "no complete release with SHA256SUMS found at $releases"
    if [ "$version" != "$newest" ]; then
      printf 'Note: %s is still uploading assets; installing %s.\n' "$newest" "$version"
    fi
    base="$releases/download/$version"
  fi

  if [ ! -s "$tmp/SHA256SUMS" ]; then
    download "$base/SHA256SUMS" "$tmp/SHA256SUMS" || fail "could not download $base/SHA256SUMS"
  fi

  installed=""
  chosen_variant=""
  for cand in $try_variants; do
    archive="triage-linux-$arch-$cand.tar.gz"
    expected=$(awk -v f="$archive" '$2 == f { print $1 }' "$tmp/SHA256SUMS")
    if [ -z "$expected" ]; then
      [ "$variant" != "auto" ] && fail "$archive not found in SHA256SUMS"
      continue
    fi

    printf 'Downloading %s (%s)...\n' "$archive" "$version"
    download "$base/$archive" "$tmp/$archive" || fail "could not download $base/$archive"

    actual=$(compute_sha256 "$tmp/$archive")
    [ "$actual" = "$expected" ] || fail "SHA256 mismatch for $archive; refusing to install"

    mkdir -p "$tmp/unpack-$cand"
    tar -xzf "$tmp/$archive" -C "$tmp/unpack-$cand" triage || fail "failed to unpack $archive"
    chmod 755 "$tmp/unpack-$cand/triage"

    if ver_out=$("$tmp/unpack-$cand/triage" --version 2>/dev/null | head -n 1); then
      installed="$ver_out"
      chosen_variant="$cand"
      mv -f "$tmp/unpack-$cand/triage" "$dir/$name"
      break
    elif [ "$variant" = "auto" ] && [ "$cand" = "gnu" ]; then
      printf 'Host C++ runtime is older than glibc build requirements; falling back to static musl build...\n'
    else
      fail "downloaded $archive could not execute on this host"
    fi
  done

  [ -n "$installed" ] || fail "could not find a runnable triage release archive"

  printf 'Installed %s (%s) -> %s/%s\n' "$installed" "$chosen_variant" "$dir" "$name"
  case ":$PATH:" in
    *":$dir:"*) ;;
    *)
      printf 'Add %s to your PATH to run triage:\n' "$dir"
      printf '  export PATH="%s:$PATH"\n' "$dir"
      ;;
  esac
}

main "$@"
