#!/bin/bash

# Script to generate .env file from CloudFormation stack outputs
# This script requires AWS CLI to be installed and configured

# Set the stack name
STACK_NAME="BDAMediaSolutionBackendStack"

# Check if AWS CLI is installed
if ! command -v aws &> /dev/null; then
    echo "Error: AWS CLI is not installed. Please install it first."
    exit 1
fi

# Check if AWS CLI is configured
if ! aws sts get-caller-identity &> /dev/null; then
    echo "Error: AWS CLI is not configured. Please run 'aws configure' first."
    exit 1
fi

# Check if jq is installed
if ! command -v jq &> /dev/null; then
    echo "Error: jq is not installed. Please install it first."
    exit 1
fi

echo "Fetching CloudFormation stack outputs for $STACK_NAME..."

# Get the stack outputs
STACK_OUTPUTS=$(aws cloudformation describe-stacks --stack-name "$STACK_NAME" --query "Stacks[0].Outputs" --output json)

# Check if the command was successful
if [ $? -ne 0 ]; then
    echo "Error: Failed to fetch stack outputs. Please check if the stack exists and you have permissions to access it."
    exit 1
fi

# Create .env file
echo "Generating .env file..."

# Remove existing .env file if it exists
if [ -f .env ]; then
    echo "Removing existing .env file..."
    rm .env
fi

# Initialize the file with a header
cat > .env << EOF
# Generated from CloudFormation stack outputs
# Do not edit this file manually
EOF

# Function to extract value by key pattern
extract_value() {
    local pattern=$1
    echo "$STACK_OUTPUTS" | jq -r ".[] | select(.OutputKey | startswith(\"$pattern\")) | .OutputValue"
}

# Extract and map the values using pattern matching
REGION_NAME=$(extract_value "RegionName")
COGNITO_USER_POOL_ID=$(extract_value "CognitoUserPoolId")
COGNITO_USER_POOL_CLIENT_ID=$(extract_value "CognitoUserPoolClientId")
COGNITO_IDENTITY_POOL_ID=$(extract_value "CognitoIdentityPoolId")
API_GATEWAY_REST_API_ENDPOINT=$(extract_value "ApiGatewayRestApiEndpoint")
S3_BUCKET_NAME=$(extract_value "BDAInputBucket")

# Append the values to the .env file
cat >> .env << EOF

VITE_REGION_NAME=$REGION_NAME
VITE_COGNITO_USER_POOL_ID=$COGNITO_USER_POOL_ID
VITE_COGNITO_USER_POOL_CLIENT_ID=$COGNITO_USER_POOL_CLIENT_ID
VITE_COGNITO_IDENTITY_POOL_ID=$COGNITO_IDENTITY_POOL_ID
VITE_API_GATEWAY_REST_API_ENDPOINT=$API_GATEWAY_REST_API_ENDPOINT
VITE_APP_NAME="Bedrock BDA Multimodal Media Solution"
VITE_S3_BUCKET_NAME=$S3_BUCKET_NAME
EOF

echo "Successfully generated .env file!"
echo "Please check the file to ensure all values are correct." 