#!/bin/bash
set -e

if [ -z "$SECRET_KEY" ]; then
    echo "Set a SECRET_KEY for \"$WORKSPACE_NAME\" decryption"
    exit 1
fi

function decrypt_file() {
    input_file=$1
    target_file=${input_file%".enc"}
    echo "Decrypting $input_file to $target_file"
    openssl enc -aes-256-cbc -d -in $input_file -out $target_file -pass pass:$SECRET_KEY
    rm -f $input_file
}

if [ -z $1 ]; then
    echo "Usage:"
    echo "  ./scripts/decrypt.sh <filePathFromProjectRoot>"
    echo "  ./scripts/decrypt.sh all"
    exit 2
elif [ "$1" == "all" ]; then
    for input_file in config/$WORKSPACE_NAME/*.tfsecrets.enc
    do
        decrypt_file $input_file
    done
else
    decrypt_file $1
fi