#!/usr/bin/env bash
# Install huskies locally on macOS: the underlying binary + a codesign-heal wrapper.
#
# After a `cp` or download the binary loses its ad-hoc signature and macOS
# SIGKILLs it silently on Apple Silicon.  This script installs the binary as
# ~/bin/huskies-bin and installs a thin wrapper at ~/bin/huskies that
# re-signs the underlying binary whenever codesign validation fails, then
# execs it.  Normal launches (already signed) are silent and zero-overhead.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
BINARY_PATH="${SCRIPT_DIR}/target/release/huskies"
BIN_DIR="${HOME}/bin"
UNDERLYING="${BIN_DIR}/huskies-bin"
WRAPPER="${BIN_DIR}/huskies"

if [ ! -f "${BINARY_PATH}" ]; then
  echo "Error: binary not found at ${BINARY_PATH}"
  echo "Run: cargo build --release"
  exit 1
fi

mkdir -p "${BIN_DIR}"

cp "${BINARY_PATH}" "${UNDERLYING}"
chmod +x "${UNDERLYING}"
echo "==> Installed binary:  ${UNDERLYING}"

cat > "${WRAPPER}" << 'WRAPPER_EOF'
#!/usr/bin/env bash
# Codesign-heal wrapper — re-signs ~/bin/huskies-bin if the signature is
# missing or invalid, then execs the binary.  Logs only when it re-signs.
BIN="${HOME}/bin/huskies-bin"

if ! codesign --verify --quiet "${BIN}" 2>/dev/null; then
    codesign -s - "${BIN}"
    echo "[codesign-heal] re-signed ~/bin/huskies-bin" >&2
fi

exec "${BIN}" "$@"
WRAPPER_EOF
chmod +x "${WRAPPER}"
echo "==> Installed wrapper: ${WRAPPER}"
