---
- hosts: localhost
  connection: local
  gather_facts: False

  vars_files:
    - test_vars.yml

  tasks:
    - block:

          ## Generating the testname for deployment
        - include_tasks: /e2e-tests/hack/create_testname.yml
        
          # RECORD START-OF-TEST IN e2e RESULT CR
        - include_tasks: /e2e-tests/hack/update_e2e_result_resource.yml
          vars:
            status: 'SOT'

        - name: Checking the status of test specific namespace.
          include_tasks: /e2e-tests/utils/k8s/status_testns.yml

        - name: Get the application label value from env
          set_fact:
            app_lkey: "{{ app_label.split('=')[0] }}"
            app_lvalue: "{{ app_label.split('=')[1] }}"

        - name: Checking whether application is running
          include_tasks: /e2e-tests/utils/k8s/status_app_pod.yml

        - name: Obtaining the loadgen pod label from env.
          set_fact:
            loadgen_lkey: "{{ loadgen_label.split('=')[0] }}"
            loadgen_lvalue: "{{ loadgen_label.split('=')[1] }}"

        - name: Replace default values/placeholder with test-specific values
          include_tasks: ./replace.yml

        - name: Checking for configmap
          shell: kubectl get configmap -n {{ app_ns }}
          register: configmap

        - name: Creating a kubernetes config map to hold the tpcc benchmark config
          shell: kubectl create configmap tpcc-config --from-file {{ tpcc_conf }} -n {{ app_ns }}
          when: "'tpcc-config' not in configmap.stdout"

        - name: Create Percona Loadgen Job
          shell: kubectl apply -f {{ percona_loadgen }} -n {{ app_ns }}

        - name: Verify load-gen pod is running
          shell: kubectl get pods -n {{ app_ns }} -l {{ loadgen_label }} -o jsonpath='{.items[0].status.phase}'
          args:
            executable: /bin/bash
          register: result
          until: "'Running' in result.stdout"
          delay: 5
          retries: 60

        - name: Getting the Percona POD name
          shell: kubectl get po -n {{ app_ns }} -l {{ app_label }} -o jsonpath='{.items[0].metadata.name}'
          register: pod_name

        - name: Verifying load-generation
          shell: kubectl exec -it {{ pod_name.stdout }} -n {{ app_ns }} -- mysql -u{{ db_user }} -p{{ db_password }} -e "show databases"
          register: output
          until: "'tpcc-' in output.stdout"
          delay: 5
          retries: 120

        - set_fact:
            flag: "Pass"

      rescue:
        - set_fact:
            flag: "Fail"

      always:
            ## RECORD END-OF-TEST IN e2e RESULT CR
        - include_tasks: /e2e-tests/hack/update_e2e_result_resource.yml
          vars:
            status: 'EOT'
