#!/usr/bin/env bash
# scripts/prereqs/install-jq.sh [--check|--dry-run]
#
# Prereq installer: jq -- the JSON processor many of this repo's operational
# scripts rely on (cloud-assert, tenant tooling, BOM/diff work). Its absence is
# a known cause of harness-gauntlet failures on under-provisioned workstations.
# Debian/Ubuntu (apt). Idempotent.
#
#   --check     report present/absent; exit 0/1
#   --dry-run   print what it would do; mutate nothing
#   (no flag)   apt-get install jq (sudo)
#
# Exit: 0 ok/installed | 1 check-failed | 2 bad args | 3 unsupported OS | 4 install failed.
# ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$HERE/lib-prereq.sh"

pq_parse_mode "$@"; rc=$?
[ "$rc" = "10" ] && { echo "usage: bash scripts/prereqs/install-jq.sh [--check|--dry-run]"; exit 0; }
[ "$rc" = "0" ] || exit "$rc"

if pq_have jq; then
  echo "OK: jq present ($(jq --version 2>/dev/null))"; exit 0
fi
echo "ABSENT: jq not on PATH"
[ "$PQ_CHECK" = "1" ] && exit 1

pq_require_apt jq || exit 3
pq_run "apt-get update" -- sudo apt-get update || { echo "FAIL: apt-get update" >&2; exit 4; }
pq_run "install: jq" -- sudo apt-get install -y jq || { echo "FAIL: package install" >&2; exit 4; }
[ "$PQ_DRYRUN" = "1" ] && { echo "  (dry-run: no changes made)"; exit 0; }
pq_have jq && { echo "INSTALLED: jq $(jq --version 2>/dev/null)"; exit 0; }
echo "FAIL: post-install check did not find jq" >&2; exit 4
