---

- name: Build Operator in Kubernetes docker container
  hosts: k8s
  vars:
    image_name: inventory.apps.fabianism.us/inventory:testing
  tasks:
  # using command so we don't need to install any dependencies
  - name: Get existing image hash
    command: docker images -q {{image_name}}
    register: prev_hash
    changed_when: false

  - name: Build Operator Image
    command: docker build -f /build/build/Dockerfile -t {{ image_name }} /build
    register: build_cmd
    changed_when: not prev_hash.stdout or (prev_hash.stdout and prev_hash.stdout not in ''.join(build_cmd.stdout_lines[-2:]))

- name: Converge
  hosts: localhost
  connection: local
  vars:
    ansible_python_interpreter: '{{ ansible_playbook_python }}'
    deploy_dir: "{{ lookup('env', 'MOLECULE_PROJECT_DIRECTORY') }}/deploy"
    pull_policy: Never
    REPLACE_IMAGE: inventory.apps.fabianism.us/inventory:testing
    custom_resource: "{{ lookup('file', '/'.join([deploy_dir, 'crds/inventory_v1alpha1_inventory_cr.yaml'])) | from_yaml }}"
  tasks:
  - name: Delete the Operator Deployment
    k8s:
      state: absent
      namespace: '{{ namespace }}'
      definition: "{{ lookup('template', '/'.join([deploy_dir, 'operator.yaml'])) }}"
    register: delete_deployment
    when: hostvars[groups.k8s.0].build_cmd.changed

  - name: Wait 30s for Operator Deployment to terminate
    k8s_facts:
      api_version: '{{ definition.apiVersion }}'
      kind: '{{ definition.kind }}'
      namespace: '{{ namespace }}'
      name: '{{ definition.metadata.name }}'
    vars:
      definition: "{{ lookup('template', '/'.join([deploy_dir, 'operator.yaml'])) | from_yaml }}"
    register: deployment
    until: not deployment.resources
    delay: 3
    retries: 10
    when: delete_deployment.changed

  - name: Create the Operator Deployment
    k8s:
      namespace: '{{ namespace }}'
      definition: "{{ lookup('template', '/'.join([deploy_dir, 'operator.yaml'])) }}"

  - name: Create the inventory.apps.fabianism.us/v1alpha1.Inventory
    k8s:
      state: present
      namespace: '{{ namespace }}'
      definition: "{{ custom_resource }}"

  - name: Wait 30s for reconciliation to run
    k8s_facts:
      api_version: '{{ custom_resource.apiVersion }}'
      kind: '{{ custom_resource.kind }}'
      namespace: '{{ namespace }}'
      name: '{{ custom_resource.metadata.name }}'
    register: cr
    until:
    - "'Successful' in (cr | json_query('resources[].status.conditions[].reason'))"
    delay: 3
    retries: 10

- import_playbook: asserts.yml
