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

- block:
  - name: create temporary build directory
    tempfile:
      suffix: build
      state: directory
    register: temp_image_directory

  - name: create empty 1g image
    command: truncate -s 1g '{{ temp_image_directory.path }}/{{ empty_image_raw }}' creates={{ empty_image_raw }}

  - name: archive raw image
    command: /usr/bin/tar -Szcf '{{ temp_image_directory.path }}/{{ empty_image_archive }}' -C '{{ temp_image_directory.path }}' '{{ empty_image_raw }}' creates={{ empty_image_archive }}

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

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

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

  - name: upload image to the bucket
    command: gsutil cp '{{ temp_image_directory.path }}/{{ empty_image_archive }}' {{ empty_image_bucket }}
    when: image_in_bucket_exists | failed

  - name: create gce image from the uploaded archive
    command: gcloud --project {{ gcloud_project }} compute images create {{ empty_image_gce }} --source-uri {{ empty_image_in_bucket }}

  - name: delete bucket with uploaded archive
    command: gsutil -m rm -r "{{ empty_image_bucket }}"
  when: empty_image_gce_exists | failed
  always:
  - name: delete temporary directory
    file:
      path: '{{ temp_image_directory.path }}'
      state: absent
