#!/usr/bin/env bash
# install-guest-helper.sh — Install the advisory guest helper onto a VM.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DRY_RUN=false
DOMAIN="${1:-}"

if [ -z "$DOMAIN" ]; then
    echo "Usage: bash tools/vm/install-guest-helper.sh <domain> [--dry-run]"
    exit 1
fi

if [[ "${2:-}" == "--dry-run" ]]; then
    DRY_RUN=true
fi

source "$SCRIPT_DIR/lib/common.sh"

helper_name=""
case "$DOMAIN" in
    sc-workstation) helper_name="atlas-index" ;;
    sc-web-server) helper_name="yardd" ;;
    sc-build-machine) helper_name="ops-telemetry-cache" ;;
    *) echo "Unknown domain: $DOMAIN"; exit 1 ;;
esac

ensure_vm_tooling

tmp_script="$(mktemp)"
cat > "$tmp_script" <<EOF
cat > /usr/local/bin/${helper_name} <<'HELPER'
#!/usr/bin/env bash
set -euo pipefail
printf '{"helper":"%s","hostname":"%s","timestamp":"%s"}\n' \
  "${helper_name}" \
  "\$(hostname)" \
  "\$(date -Iseconds)"
HELPER
chmod 755 /usr/local/bin/${helper_name}
EOF

info "Installing guest helper ${helper_name} on ${DOMAIN}"
guest_run_sudo_script "$DOMAIN" "$tmp_script"
rm -f "$tmp_script"
ok "${DOMAIN}: helper ${helper_name} installed"
