#!/bin/bash

source "$ROOT_PATH"/scripts/common.sh
set -eo pipefail

# Function to handle errors
handle_error() {
    echo_red_bg "Error: $1"
    exit 1
}

cd $WORK_DIR || handle_error "failed to cd $WORK_DIR"
# echo "Terragrunt Format..."
# terragrunt hclfmt --terragrunt-check

if [ $COMMAND == 'validate' ]; then
    echo_red "Terragrunt Validate..."
    terragrunt validate $ARGS || handle_error "failed to validate terragrunt files"
elif [ $COMMAND == 'init' ]; then
    echo_red "Terragrunt Init..."
    terragrunt init $ARGS || handle_error "failed to initialize terragrunt configuration"
elif [ $COMMAND == 'plan' ]; then
    echo_red "Terragrunt Plan..."
    terragrunt plan -out=saved_plan $ARGS || handle_error "failed to save terragrunt plan outputs"
elif [ $COMMAND == 'apply' ]; then
    echo_red "Terragrunt Apply..."
    terragrunt apply -auto-approve saved_plan $ARGS || handle_error "failed to apply terragrunt configuration"
elif [ $COMMAND == 'plan-destroy' ]; then
    echo_red "Terragrunt Plan for Destroy..."
    terragrunt plan -destroy -out=saved_plan $ARGS || handle_error "failed to save terragrunt destroy plan ouputs"
elif [ $COMMAND == 'destroy' ]; then
    echo_red "Terragrunt Destroy..." || handle_error "failed to destroy terragrunt resources"
    terragrunt destroy -auto-approve $ARGS
else
    echo_red "Terragrunt command was not recognized. Please, check your command!!!"
fi