#!/bin/bash

set -eux

### --start_docs
## --------------------------------------------------
## Checkout custom tripleo heat templates
## --------------------------------------------------

## ########################
## Prepare Your Environment
## ########################

{% if tht_templates_repo|trim and tht_templates_path not in ['', '/'] %}
## * Clone the t-h-t templates if needed.
## ::

rm -rf {{ tht_templates_path }}
chmod 755 $HOME
git clone --depth 1 {% if tht_templates_branch|trim %}-b {{ tht_templates_branch }} \
    --single-branch{% endif %} {{ tht_templates_repo }} {{ tht_templates_path }}

{% if tht_templates_refspec|trim %}
## * Checkout an open t-h-t review if specified
##    (this will stomp on the tht_templates_branch, so only one should be used).
## ::

pushd {{ tht_templates_path }}
git fetch {{ tht_templates_repo }} {{ tht_templates_refspec }} && git checkout FETCH_HEAD
popd
{% endif %}

{% if not composable_scenario|trim == '' %}
## * If desired composable scenario isn't present in the checked-out
##   code, but is present in RPM, copy the scenario from RPM location.
## ::
if [ ! -e "{{ tht_templates_path }}/ci/environments/{{ composable_scenario }}" \
    -a -e "/usr/share/openstack-tripleo-heat-templates/ci/environments/{{ composable_scenario }}" ]; then
    cp "/usr/share/openstack-tripleo-heat-templates/ci/environments/{{ composable_scenario }}" \
        "{{ tht_templates_path }}/ci/environments/{{ composable_scenario }}"
fi
{% endif %}
{% if not upgrade_composable_scenario|trim == '' %}
if [ ! -e "{{ tht_templates_path }}/ci/environments/{{ upgrade_composable_scenario }}" \
    -a -e "/usr/share/openstack-tripleo-heat-templates/ci/environments/{{ upgrade_composable_scenario }}" ]; then
    cp "/usr/share/openstack-tripleo-heat-templates/ci/environments/{{ upgrade_composable_scenario }}" \
        "{{ tht_templates_path }}/ci/environments/{{ upgrade_composable_scenario }}"
fi
{% endif %}

{% endif %}

{% if download_templates_rpm and tht_templates_path|trim %}
## * Download the t-h-t package.
## ::
rm -rf {{ tht_templates_path }}
mkdir -p {{ working_dir }}/{{ tht_templates_path }}/downloaded-tht-rpm
pushd {{ working_dir }}/{{ tht_templates_path }}/downloaded-tht-rpm

tht_rpm_name=$(curl {{ tht_rpm_url }} | grep "openstack-tripleo-heat-templates" | grep "noarch.rpm" | grep -v "tripleo-heat-templates-compat" | sed "s/^.*>openstack-tripleo-heat-templates/openstack-tripleo-heat-templates/" | cut -d "<" -f1)
curl -o {{ working_dir }}/{{ tht_templates_path }}/downloaded-tht-rpm/$tht_rpm_name {{ tht_rpm_url }}/$tht_rpm_name

## * Unpack tht sources
## ::

rpm2cpio $(ls -1 *.rpm | grep $tht_rpm_name) | cpio -ivdm
cp -R usr/share/openstack-tripleo-heat-templates {{ tht_templates_path }}
popd
{% endif %}

{{ prep_post_hook_script }}

### --stop_docs
