#!/usr/bin/env bash

set -e

# {{ ansible_managed }}

app_update="{{ debops_api__app_update | bool | lower }}"
app_repo_dest="{{ debops_api__app_repo_dest }}"
input_data_repo_dest="{{ debops_api__input_data_repo_dest }}"

if [ "${app_update}" = "true" ] ; then
    git -C "${app_repo_dest}" pull --ff-only
fi

git -C "${input_data_repo_dest}" pull --ff-only
git -C "${input_data_repo_dest}" submodule update --init

# shellcheck disable=SC1117
read -r debops_api_command << EOF
{% macro flatten_app_parameters_list(nested_list) %}{# [[[ #}
{% for item in nested_list %}
{%   if item is string %}
{%     set _ = debops_api__tpl_app_parameters_flattened.append(item) %}
{%   else %}
{%     set _ = flatten_app_parameters_list(item) %}
{%   endif %}
{% endfor %}
{% endmacro %}{# ]]] #}
{% set debops_api__tpl_app_parameters_flattened = [ 'linebreak' ] %}
{% set _ = flatten_app_parameters_list(
   (debops_api__app_parameters | list) +
   [ '--role-path', debops_api__input_data_role_path, 'linebreak' ] +
   [ '--api-dir', debops_api__public_api_dir ]
) %}
python{{ debops_api__python_version|string }} {{ (debops_api__app_repo_dest + "/bin/debops-api") | quote }} {{ debops_api__tpl_app_parameters_flattened
      | map("quote") | map("regex_replace", "^linebreak$", "\\\n    ") | join(" ") }}
EOF

eval "${debops_api_command}"
