---
# yaml-language-server: $schema=https://taskfile.dev/schema.json
version: "3"

vars:
  PYTHON_BIN: python3

env:
  PATH: "{{.ROOT_DIR}}/.venv/bin:$PATH"
  VIRTUAL_ENV: "{{.ROOT_DIR}}/.venv"
  ANSIBLE_COLLECTIONS_PATH: "{{.ROOT_DIR}}/.venv/galaxy"
  ANSIBLE_ROLES_PATH: "{{.ROOT_DIR}}/.venv/galaxy/ansible_roles"
  ANSIBLE_VARS_ENABLED: "host_group_vars,community.sops.sops"

tasks:

  deps:
    desc: Set up Ansible dependencies for the environment
    cmds:
      - task: .venv

  run:
    desc: Run an Ansible playbook for configuring a cluster
    summary: |
      Args:
        cluster: Cluster to run command against (required)
        playbook: Playbook to run (required)
    prompt: Run Ansible playbook '{{.playbook}}' against the '{{.cluster}}' cluster... continue?
    deps: ["deps"]
    cmd: |
      .venv/bin/ansible-playbook \
        --inventory {{.ANSIBLE_DIR}}/{{.cluster}}/inventory/hosts.yaml \
        {{.ANSIBLE_DIR}}/{{.cluster}}/playbooks/{{.playbook}}.yaml {{.CLI_ARGS}}
    preconditions:
      - { msg: "Argument (cluster) is required", sh: "test -n {{.cluster}}" }
      - { msg: "Argument (playbook) is required", sh: "test -n {{.playbook}}" }
      - { msg: "Venv not found", sh: "test -d {{.ROOT_DIR}}/.venv" }
      - { msg: "Inventory not found", sh: "test -f {{.ANSIBLE_DIR}}/{{.cluster}}/inventory/hosts.yaml" }
      - { msg: "Playbook not found", sh: "test -f {{.ANSIBLE_DIR}}/{{.cluster}}/playbooks/{{.playbook}}.yaml" }

  .venv:
    internal: true
    cmds:
      - true && {{.PYTHON_BIN}} -m venv {{.ROOT_DIR}}/.venv
      - .venv/bin/python3 -m pip install --upgrade pip setuptools wheel
      - .venv/bin/python3 -m pip install --upgrade --requirement {{.ANSIBLE_DIR}}/requirements.txt
      - .venv/bin/ansible-galaxy install --role-file "{{.ANSIBLE_DIR}}/requirements.yaml" --force
    sources:
      - "{{.ANSIBLE_DIR}}/requirements.txt"
      - "{{.ANSIBLE_DIR}}/requirements.yaml"
    generates:
      - "{{.ROOT_DIR}}/.venv/pyvenv.cfg"