#!/usr/bin/env bash
set -euo pipefail

script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
inventory=${1:-"$script_dir/inventory.yml"}

if [[ ! -f "$inventory" ]]; then
  printf 'Inventory not found: %s\nCopy %s/inventory.example.yml and edit it first.\n' "$inventory" "$script_dir" >&2
  exit 1
fi
inventory=$(realpath -- "$inventory")

if [[ -z "${K3S_TOKEN:-}" ]]; then
  printf 'K3S_TOKEN must be supplied through the environment.\n' >&2
  exit 1
fi

if ! command -v ansible-playbook >/dev/null 2>&1; then
  printf 'ansible-playbook is required. Install ansible-core on this operator machine.\n' >&2
  exit 1
fi

cd "$script_dir"
ansible-galaxy collection install --requirements-file requirements.yml
ansible-playbook --inventory "$inventory" site.yml
