#!/bin/bash

set -o nounset

PATH="/usr/bin:/usr/local/bin"

# Obtain the vault variables 
mapfile -t VAULT_VARS < <(
    LC_ALL=C.UTF-8 ansible-vault view stack.env.vault |
    sed -n 's/#.*//; /VAULT_/p' |
    sed 's/:/=/; s/: /=/' |
    cut -d= -f1
)

printf "\n### Variables from the vault are:\n"
printf "%s\n" "${VAULT_VARS[@]}"

VAULT_PATTERN=$(IFS='|'; echo "${VAULT_VARS[*]}")

printf "\n### Variables defined with with vault variables are:\n"
grep -E "\\\$\{(${VAULT_PATTERN})[:?-]" compose.yaml
printf "\n"

# Find the left-hand variable names, as these are the ones to be excluded.
mapfile -t EXCLUDE_VARS < <(
    grep -E "\\\$\{(${VAULT_PATTERN})[:?-]" compose.yaml |
    sed 's/^[[:blank:]]*//; s/:.*//; s/- //; s/=.*//'
)

printf "\n### Variables to exclude are:\n"
printf "%s\n" "${EXCLUDE_VARS[@]}"

EXCLUDE_PATTERN=$(IFS='|'; echo "${EXCLUDE_VARS[*]}")

printf "\n### Processed compose file without secret variables\n\n"
docker-compose-vault config | grep -vE "^[[:space:]]*(-[[:space:]]*)?(${EXCLUDE_PATTERN})[=:]"

