#!/bin/bash

set -eo pipefail

# Environment Variables
export ENV_NAME=local
export NODE_ENV=development
export AWS_REGION=us-east-1
export AWS_ACCOUNT_ID=000000000000
export ABSOLUTE_BUILD_FUNCTIONS_PATH="$ABSOLUTE_PATH/dist/functions"

# Function to color pipeline logs
function echo_red_bg() {
  echo -e "\e[41m$1\e[0m"
}

function echo_red() {
  echo -e "\e[31m$1\e[0m"
}

function echo_green() {
  echo -e "\e[32m$1\e[0m"
}

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

# Common Deployment Function
function deploy_component() {
  local component_name="$1"
  local terragrunt_dir="$2"

  echo_red "Deploying $component_name ..."
  cd "$terragrunt_dir" || handle_error "failed to change directory for $terragrunt_dir"

  if [[ -n "$ABSOLUTE_BUILD_FUNCTIONS_PATH" ]]; then
    export LAMBDA_MOUNT_CWD="$ABSOLUTE_BUILD_FUNCTIONS_PATH/$(basename "$(pwd)")"
    export TF_VAR_s3_existing_package='{"bucket": "hot-reload", "key": "'$LAMBDA_MOUNT_CWD'"}'
  fi

  terragrunt apply -auto-approve || handle_error "failed to apply terragrunt configuration for $component_name"

  echo_green "Deployment is successfully finished for $component_name"

  cd -
}

# LocalStack Deployments
deploy_component "LocalStack VPC" "infra/localstack/network/vpc"
deploy_component "LocalStack APIGWVPCEndpoint" "infra/localstack/network/components/vpc-endpoint/api-gateway"

# Shared Deployments
deploy_component "SharedNetwork" "infra/common/network"

# SWG Deployments
deploy_component "FetchProfileSqs" "infra/swg-sqs-fetch-profile"
deploy_component "FetchProfileLambda" "infra/swg-lambda-fetch-profile"
deploy_component "TopicSubscriptions" "infra/subscriptions"
deploy_component "ComputeProfileSqs" "infra/swg-sqs-compute-profile"
deploy_component "ComputeProfileLambda" "infra/swg-lambda-compute-profile"

npm run build:watch