---
# tasks file for AnsibleAutomationPlatformAzureBilling
- name: Set custom azure billing image
  set_fact:
    _custom_image: "{{ image }}:{{ image_version }}"
  when:
    - image is defined
    - image_version is defined

- name: Set azure billing image
  set_fact:
    azure_billing_image: "{{ _custom_image | default(lookup('env', 'RELATED_IMAGE_AZURE_BILLING')) }}"

- name: Get the automation controller database secret
  kubernetes.core.k8s_info:
    kind: Secret
    namespace: '{{ ansible_operator_meta.namespace }}'
    name: '{{ automationcontroller_db_secret }}'
  register: automationcontroller_db_config
  no_log: true

- name: Get the azure billing database secret
  kubernetes.core.k8s_info:
    kind: Secret
    namespace: '{{ ansible_operator_meta.namespace }}'
    name: '{{ azure_billing_db_secret }}'
  register: azure_billing_db_config
  no_log: true

- name: Store Databases Configuration
  set_fact:
    automationcontroller_db_user: "{{ automationcontroller_db_config['resources'][0]['data']['username'] | b64decode }}"
    automationcontroller_db_pass: "{{ automationcontroller_db_config['resources'][0]['data']['password'] | b64decode }}"
    automationcontroller_db_name: "{{ automationcontroller_db_config['resources'][0]['data']['database'] | b64decode }}"
    automationcontroller_db_port: "{{ automationcontroller_db_config['resources'][0]['data']['port'] | b64decode }}"
    automationcontroller_db_host: "{{ automationcontroller_db_config['resources'][0]['data']['host'] | b64decode }}"
    azure_billing_db_user: "{{ azure_billing_db_config['resources'][0]['data']['username'] | b64decode }}"
    azure_billing_db_pass: "{{ azure_billing_db_config['resources'][0]['data']['password'] | b64decode }}"
    azure_billing_db_name: "{{ azure_billing_db_config['resources'][0]['data']['database'] | b64decode }}"
    azure_billing_db_port: "{{ azure_billing_db_config['resources'][0]['data']['port'] | b64decode }}"
    azure_billing_db_host: "{{ azure_billing_db_config['resources'][0]['data']['host'] | b64decode }}"
  no_log: true

- name: Apply Resources
  k8s:
    apply: true
    definition: "{{ lookup('template', item + '.yaml.j2') }}"
    wait: true
  loop:
    - 'secret'
    - 'cronjob'
  no_log: true

- name: Update AnsibleAutomationPlatformAzureBilling status
  operator_sdk.util.k8s_status:
    api_version: platform.ansible.com/v1alpha1
    kind: AnsibleAutomationPlatformAzureBilling
    name: '{{ ansible_operator_meta.name }}'
    namespace: '{{ ansible_operator_meta.namespace }}'
    status:
      azureBillingCronJob: "{{ azure_billing_cronjob_name }}"
      azureBillingImage: "{{ azure_billing_image }}"
      azureBillingSettingsSecret: "{{ ansible_operator_meta.name }}-settings"
