#!/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:-2.17.14}"
ANSIBLE_LINT_VERSION="${ANSIBLE_LINT_VERSION:-24.12.2}"
RECREATE=0

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 [ "$RECREATE" = "1" ] || [ ! -x "$VENV_DIR/bin/python" ]; then
  python3 -m venv --clear "$VENV_DIR"
else
  python3 -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"
