---
- hosts: localhost
  connection: local
  vars_files:
    - secrets.yaml
  gather_facts: true
  vars:
    clusters:
      - karpenter
      - cas
    load_test_targets: "{{ lookup('env', 'LOAD_TEST_TARGET') | default('') | split(',') }}"
    cleanup_executed: false

  pre_tasks:
    - name: Set fact for IBM and AWS tasks based on env
      set_fact:
        run_iks: "{{ 'IBM_CLOUD' in load_test_targets }}"
        run_eks: "{{ 'AWS' in load_test_targets }}"
      tags:
        - billing
        - setup
        - config 
        - benchmark 
        - teardown

    - name: Generate UUID
      ansible.builtin.command: uuidgen
      register: generated_uuid
      tags:
        - billing
        - setup
        - config
        - benchmark
        - teardown

    - name: Set UUID fact
      ansible.builtin.set_fact:
        tag_uuid: "{{ generated_uuid.stdout }}"
      tags:
        - billing
        - setup
        - config 
        - benchmark 
        - teardown

  tasks:
    - name: Run experiment with automatic cleanup on failure
      block:
        - name: Bootstrap clusters
          include_role:
            name: cluster_bootstrap
          when: run_iks or run_eks
          vars:
            cloud_provider: "{{ 'iks' if run_iks else 'eks' }}"
          tags: 
            - setup

        - name: Setup clusters
          include_role:
            name: cluster_setup
          when: run_iks or run_eks
          vars:
            cloud_provider: "{{ 'iks' if run_iks else 'eks' }}"
          tags: 
            - config

        - name: Run benchmarks
          include_role:
            name: benchmarking
          when: run_iks or run_eks
          vars:
            cloud_provider: "{{ 'iks' if run_iks else 'eks' }}"
            workload_scenario: "{{ lookup('env', 'WORKLOAD_SCENARIO') | default('homogeneous') }}"
          tags:
            - benchmark
            - billing

      rescue:
        - name: Set cleanup executed flag
          set_fact:
            cleanup_executed: true

        - name: Cleanup on failure
          include_role:
            name: cluster_teardown
          when: run_iks or run_eks
          vars:
            cloud_provider: "{{ 'iks' if run_iks else 'eks' }}"

      always:
        - name: Normal teardown
          include_role:
            name: cluster_teardown
          when: (run_iks or run_eks) and not cleanup_executed
          vars:
            cloud_provider: "{{ 'iks' if run_iks else 'eks' }}"
          tags:
            - teardown
