---
- name: check if rhel image is already present in gce
  command: gcloud --project {{ gcloud_project }} compute images describe {{ rhel_image_gce }}
  register: rhel_image_gce_exists
  changed_when: false
  ignore_errors: true

- block:
  - name: convert qcow2 image to raw image
    command: qemu-img convert -p -S 4096 -f qcow2 -O raw '{{ rhel_image_path }}' '{{ rhel_image_raw }}' creates='{{ rhel_image_raw }}'

  - name: archive raw image
    command: /usr/bin/tar -Szcf {{ rhel_image_archive }} -C '{{ rhel_image_dir }}' {{ rhel_image_raw | basename }} creates='{{ rhel_image_archive }}'

  - name: check if a bucket in gcs exists
    command: gsutil ls -p {{ gcloud_project }} {{ rhel_image_bucket }}
    register: bucket_exists
    ignore_errors: true

  - name: create a bucket in gcs
    command: gsutil mb -p {{ gcloud_project }} -l {{ gcloud_region }} {{ rhel_image_bucket }}
    when: bucket_exists | failed

  - name: check if the bucket contains image
    command: gsutil ls -p {{ gcloud_project }} {{ rhel_image_in_bucket }}
    register: image_in_bucket_exists
    ignore_errors: true

  - name: upload image to the bucket
    command: gsutil -o GSUtil:parallel_composite_upload_threshold=150M cp '{{ rhel_image_archive }}' {{ rhel_image_bucket }}
    when: image_in_bucket_exists | failed

  - name: create gce image from the uploaded archive
    gce_img:
      name: '{{ rhel_image_gce }}'
      family: '{{ rhel_image_gce_family }}'
      source: '{{ rhel_image_in_bucket }}'
      state: present

  - name: delete bucket with uploaded archive
    command: gsutil -m rm -r {{ rhel_image_bucket }}

  - name: delete temporary archive and raw image
    file:
      path: '{{ item }}'
      state: absent
    with_items:
    - '{{ rhel_image_archive }}'
    - '{{ rhel_image_raw }}'
  when: rhel_image_gce_exists | failed
