#!/usr/bin/env bash
# 建立 AWOOOI Ansible 驗證工具鏈。
# 用途：讓本機、CI、重開機恢復接手者都用同一組 pinned 版本跑 ansible-validate.sh。

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT_DIR"

VENV_DIR="${ANSIBLE_VALIDATION_VENV:-/tmp/awoooi-ansible-venv}"
ANSIBLE_CORE_VERSION="${ANSIBLE_CORE_VERSION:-}"
ANSIBLE_LINT_VERSION="${ANSIBLE_LINT_VERSION:-}"
RECREATE=0
PYTHON_BIN="${ANSIBLE_VALIDATION_PYTHON:-}"

usage() {
  cat <<'USAGE'
Usage: bash scripts/ops/bootstrap-ansible-validation-env.sh [--recreate]

建立 / 更新 AWOOOI Ansible 驗證 venv。

Environment:
  ANSIBLE_VALIDATION_VENV   venv 位置，預設 /tmp/awoooi-ansible-venv
  ANSIBLE_CORE_VERSION      ansible-core 版本，預設 2.17.14
  ANSIBLE_LINT_VERSION      ansible-lint 版本，預設 24.12.2

Options:
  --recreate                重新建立 venv；用於 CI 或舊 venv metadata 損壞時
  -h, --help                顯示說明

驗證方式：
  PATH="${ANSIBLE_VALIDATION_VENV:-/tmp/awoooi-ansible-venv}/bin:$PATH" \
    bash scripts/ops/ansible-validate.sh
USAGE
}

for arg in "$@"; do
  case "$arg" in
    --recreate)
      RECREATE=1
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $arg" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [ -z "$PYTHON_BIN" ]; then
  for candidate in python3.11 python3.10 python3; do
    if command -v "$candidate" >/dev/null 2>&1; then
      PYTHON_BIN="$(command -v "$candidate")"
      break
    fi
  done
fi

if [ -z "$PYTHON_BIN" ]; then
  echo "python3 not found" >&2
  exit 1
fi

if ! "$PYTHON_BIN" - <<'PY'
import sys
raise SystemExit(0 if sys.version_info >= (3, 10) else 1)
PY
then
  ANSIBLE_CORE_VERSION="${ANSIBLE_CORE_VERSION:-2.15.13}"
  ANSIBLE_LINT_VERSION="${ANSIBLE_LINT_VERSION:-24.2.3}"
else
  ANSIBLE_CORE_VERSION="${ANSIBLE_CORE_VERSION:-2.17.14}"
  ANSIBLE_LINT_VERSION="${ANSIBLE_LINT_VERSION:-24.12.2}"
fi

echo "ANSIBLE_VALIDATION_PYTHON=$PYTHON_BIN"

if [ "$RECREATE" = "1" ] || [ ! -x "$VENV_DIR/bin/python" ]; then
  "$PYTHON_BIN" -m venv --clear "$VENV_DIR"
else
  "$PYTHON_BIN" -m venv "$VENV_DIR"
fi

"$VENV_DIR/bin/python" -m pip install --upgrade pip wheel
"$VENV_DIR/bin/python" -m pip install \
  "ansible-core==${ANSIBLE_CORE_VERSION}" \
  "ansible-lint==${ANSIBLE_LINT_VERSION}"

"$VENV_DIR/bin/ansible-playbook" --version | head -1
"$VENV_DIR/bin/ansible-lint" --version
echo "ANSIBLE_VALIDATION_VENV_READY=$VENV_DIR"
echo "NEXT: PATH=\"$VENV_DIR/bin:\$PATH\" bash scripts/ops/ansible-validate.sh"
