#!/usr/bin/env bash

set -eo pipefail

IFS=$'\n'
ENTRIES=$(yq -o=json '.template' ${IACD_DOCUMENT} | jq -c '.[]')

for entry in $ENTRIES; do
    entry_name=$(echo "${entry}" | jq -r '.name')
    entry_template="${IACD_PWD}/"$(echo "${entry}" | jq -r '.template')
    entry_config=$(echo "${entry}" | jq -r '.config')
    if [ -f "${entry_config}" ]; then
        entry_config_path="${entry_config}"
    else
        entry_config_path="${IACD_PWD}/${entry_config}"
    fi
    entry_mode=$(echo "${entry}" | jq -r '.mode')
    entry_ownership=$(echo "${entry}" | jq -r '.ownership')

    case ${1} in
        "create" | "update")
            cat "${entry_config_path}" | yq -o=json . | tpl -f ${entry_template} > ${entry_name}
            chown "${entry_ownership}" "${entry_name}"
            chmod "${entry_mode}" "${entry_name}"
            echo "Template ${entry_name} created (or updated)"
            ;;
        "delete")
            rm -f "${entry_name}"
            echo "Template ${entry_name} deleted"
            ;;
        "compare")
            diff -q <(cat "${entry_config_path}" | yq -o=json . | tpl -f ${entry_template}) "${entry_name}"
            ;;
    esac
done
