#!/usr/bin/env bash
# Build HSP from source and install the binary to ~/.local/bin/hsp
set -euo pipefail

REPO_URL="${HSP_REPO_URL:-https://github.com/maximilianwruhs-cyber/HSP.git}"
SRC_DIR="${HSP_SRC_DIR:-$HOME/github-clone/HSP}"
BIN_DIR="${HSP_BIN_DIR:-$HOME/.local/bin}"
BIN="$BIN_DIR/hsp"

need() {
  command -v "$1" >/dev/null 2>&1 || {
    echo "hsp-pi: missing dependency: $1" >&2
    exit 1
  }
}

need git
need cargo

if [[ -x "$SRC_DIR/hsp-rs/target/release/hsp" ]]; then
  echo "hsp-pi: using existing build at $SRC_DIR"
elif [[ -d "$SRC_DIR/.git" ]]; then
  echo "hsp-pi: building in $SRC_DIR"
  cargo build --release --manifest-path "$SRC_DIR/hsp-rs/Cargo.toml"
else
  TMP="$(mktemp -d)"
  trap 'rm -rf "$TMP"' EXIT
  echo "hsp-pi: cloning $REPO_URL"
  git clone --depth 1 "$REPO_URL" "$TMP/HSP"
  cargo build --release --manifest-path "$TMP/HSP/hsp-rs/Cargo.toml"
  SRC_DIR="$TMP/HSP"
fi

mkdir -p "$BIN_DIR"
install -m 755 "$SRC_DIR/hsp-rs/target/release/hsp" "$BIN"
echo "hsp-pi: installed $BIN"
"$BIN" --help | head -8
