#!/usr/bin/env bash
# Abort on any error. Without this, a failure to create the tmp backup stack
# (e.g. when the overlay stack is locked) is silently ignored and the overlay
# stack's own config keys are never restored after being overwritten by the
# source stack, leaving it as a pure copy of the source.
set -euo pipefail

source_stack=$1
overlay_stack=$2

function get_stack_config_array() {
    stack=$1
    local configs=`pulumi config --json -s $stack --show-secrets`
    # Only extract keys of overlay stack to avoid parsing error.
    configs=`printf "%s"  "$configs" | jq -r 'to_entries | map("\(.key)") | join(" ")'`

    configs=( $configs )
    echo "${configs[@]}"
}

# Get the list of configs in the overlay stack
overlay_configs=( $(get_stack_config_array $overlay_stack) )

pulumi stack init tmp_$overlay_stack --copy-config-from $overlay_stack

# Cover all the configs using the source stack to avoid historical configs remaining
pulumi config cp -s $source_stack -d $overlay_stack

for pair in "${overlay_configs[@]}"
do
    key=${pair%%=*}

    echo "executing: pulumi config cp $key -s tmp_$overlay_stack -d $overlay_stack"
    pulumi config cp $key -s tmp_$overlay_stack -d $overlay_stack
done

pulumi stack rm tmp_$overlay_stack --non-interactive --yes
pulumi stack select $overlay_stack
