#!/bin/bash
#
# Apply post undercloud {{ current_release }} 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 current_release in ffu_undercloud_releases[0] %}
{% for bugs in post_ffu_undercloud_upgrade_1st_release|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 current_release in ffu_undercloud_releases[1] %}
{% for bugs in post_ffu_undercloud_upgrade_2nd_release|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 current_release in ffu_undercloud_releases[2] %}
{% for bugs in post_ffu_undercloud_upgrade_3rd_release|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 %}
