#!/bin/bash
#
# Apply upgrade workarounds
set -euo pipefail

function apply_patch {
    local patch_dir=$1
    local patch_id=$2

    curl -4 https://review.openstack.org/changes/${patch_id}/revisions/current/patch?download | \
        base64 -d > /tmp/patch.txt

    if sudo patch --dry-run --reverse --force -d ${patch_dir} -p1 < /tmp/patch.txt >/dev/null 2>&1
    then
        echo "Patch ${patch_id} already applied, skipping"
    else
        sudo patch -Ns  -d ${patch_dir} -p1 < /tmp/patch.txt
    fi
}

{% if 'pre_ffu_undercloud_upgrade_workarounds' in item %}
{% for bugs in pre_ffu_undercloud_upgrade_workarounds|default([]) %}
{% for key, value in bugs.items() %}
echo {{ key }}
{% if value.patch %}
apply_patch {{ value.basedir }} {{ value.id }}
{% else %}
{{ value.command }}

{% endif %}
{% endfor %}
{% endfor %}

{% elif 'post_ffu_undercloud_upgrade_workarounds' in item %}
{% for bugs in post_ffu_undercloud_upgrade_workarounds|default([]) %}
{% for key, value in bugs.items() %}
echo {{ key }}
{% if value.patch %}
apply_patch {{ value.basedir }} {{ value.id }}
{% else %}
{{ value.command }}

{% endif %}
{% endfor %}
{% endfor %}

{% elif 'pre_ffu_overcloud_prepare_workarounds' in item %}
{% for bugs in pre_ffu_overcloud_prepare_workarounds|default([]) %}
{% for key, value in bugs.items() %}
echo {{ key }}
{% if value.patch %}
apply_patch {{ value.basedir }} {{ value.id }}
% else %}
{{ value.command }}

{% endif %}
{% endfor %}
{% endfor %}

{% elif 'pre_ffu_overcloud_run_workarounds' in item %}
{% for bugs in pre_ffu_overcloud_run_workarounds|default([]) %}
{% for key, value in bugs.items() %}
echo {{ key }}
{% if value.patch %}
apply_patch {{ value.basedir }} {{ value.id }}
{% else %}
{{ value.command }}

{% endif %}
{% endfor %}
{% endfor %}

{% elif 'pre_ffu_overcloud_upgrade_workaround' in item %}
{% for bugs in pre_ffu_overcloud_upgrade_workaround|default([]) %}
{% for key, value in bugs.items() %}
echo {{ key }}
{% if value.patch %}
apply_patch {{ value.basedir }} {{ value.id }}
{% else %}
{{ value.command }}

{% endif %}
{% endfor %}
{% endfor %}

{% elif 'pre_ffu_overcloud_converge_workarounds' in item %}
{% for bugs in pre_ffu_overcloud_converge_workarounds|default([]) %}
{% for key, value in bugs.items() %}
echo {{ key }}
{% if value.patch %}
apply_patch {{ value.basedir }} {{ value.id }}
{% else %}
{{ value.command }}

{% endif %}
{% endfor %}
{% endfor %}

{% elif 'pre_ffu_overcloud_ceph_workarounds' in item %}
{% for bugs in pre_ffu_overcloud_ceph_workarounds|default([]) %}
{% for key, value in bugs.items() %}
echo {{ key }}
{% if value.patch %}
apply_patch {{ value.basedir }} {{ value.id }}
{% else %}
{{ value.command }}

{% endif %}
{% endfor %}
{% endfor %}

{% endif %}
