- fail:
    msg: "OS build metadata should not be overwritten during live updates"
  when: is_live_update

- name: Check if in git repo
  command: "git rev-parse --is-inside-work-tree"
  delegate_to: localhost
  register: git_is_inside_result
  failed_when: git_is_inside_result.rc not in (0, 128)

- block:

  - name: Check for local repo changes
    # --exit-code: exit with 1 if there were differences, 0 otherwise.
    command: "git diff HEAD --exit-code"
    delegate_to: localhost
    register: git_diff_result
    failed_when: git_diff_result.rc > 1

  - name: Check driving repo git SHA
    command: "git rev-parse HEAD"
    delegate_to: localhost
    register: git_rev_parse_result
    failed_when: git_rev_parse_result.rc > 1

  - set_fact:
      driving_repo_revision: "{{ git_rev_parse_result.stdout }}"
      driving_local_changes_diff: "{{ git_diff_result.stdout }}"

  when: git_is_inside_result.rc == 0

# On imaging servers running zimage from the system installation, which is not a git repository
# git_rev_parse_output and git_diff_output are created by setup.py sdist
- block:

  - set_fact:
      driving_repo_revision: "{{ lookup('file', '../../git_rev_parse_output') }}"
      driving_local_changes_diff: "{{ lookup('file', '../../git_diff_output') }}"

  when: git_is_inside_result.rc != 0

- name: Write local changes to metadata file
  copy:
    content: "{{ driving_local_changes_diff }}"
    dest:  "{{ asset_root_directory }}/etc/zoox/{{ asset_type }}_local_changes.diff"

- name: Write metadata file
  template:
    src: metadata.yml
    dest: "{{ asset_root_directory }}/etc/zoox/{{ asset_type }}_metadata.yml"
