#!/bin/bash -eu

#########
# LEGAL #
######### 

# Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

### DESCRIPTION ###

# This script prepares the AWS CloudFormation templates to deploy the end-to-end
# mortgage processing flow using Amazon Bedrock

#############
### USAGE ###
#############

# 0. Call the script from the root of the repo:
#       Syntax: 
#       $ bash ./deploy.sh [region] [deployment_bucket_name]
#       Example:
#       $ bash ./deploy.sh us-east-1 my-mortgage-flow-stack-deployment-bucket
# 1. Echo Deployment Parameters
#       To confirm the deployment parameters and make a go/no go launch decision
# 2. Create S3 bucket for deployment artifacts (if needed)
# 3. Update the CloudFormation templates with deployment bucket name
#        Note: this deploy.sh is for a SINGLE REGION deployment

#####################################
### 1. ECHO DEPLOYMENT PARAMETERS ###
#####################################

## Enter Deployment Checks

# Check for args > 0
#if [[ $# -eq 0 ]] ; then
#    echo "No arguments supplied"
#    echo
#    echo "Usage: bash ./deploy.sh [region] [deployment_bucket_name]"
#    exit 1
#fi

#####################################

## AWS Deployment Region
AWS_REGION=${1:-us-east-1}
# Need to add location constraint if region is not us-east-1. Otherwise, leave it blank
LOCATION_CONSTRAINT=$([ ${AWS_REGION} != "us-east-1" ] && echo "--create-bucket-configuration LocationConstraint=${AWS_REGION}" || echo "")
#####################################

AWS="aws --output=text --region ${AWS_REGION}"
ACCOUNT_ID=$(${AWS} sts get-caller-identity --query 'Account')

#####################################
# Name of Amazon S3 Bucket used for CloudFormation deployments

DEPLOYMENT_BUCKET=${2:-mortgage-flow-deployment-${ACCOUNT_ID}-${AWS_REGION}}

#####################################

## Echo Deployment Parameters
echo "[*] Verifying deployment parameters..."
echo "[X] Account ID: ${ACCOUNT_ID}"
echo "[X] Region: ${AWS_REGION}"
echo "[X] Deployment bucket name: ${DEPLOYMENT_BUCKET}"

#####################################
### 2. CREATE DEPLOYMENT BUCKET  ###
#####################################
# Do we have to create the bucket?
_BUCKETS=$(for _BUCKET in $(${AWS} s3api list-buckets --query 'Buckets[].Name'); do echo $_BUCKET; done)
if [ -z "$(grep "${DEPLOYMENT_BUCKET}" <<< ${_BUCKETS} || true)" ]; then
  echo -n "[!] Create new bucket '${DEPLOYMENT_BUCKET}' ? [Y/n] "
  read ANS
  if [ -z "${ANS}" -o "${ANS:0:1}" = "Y" -o "${ANS:0:1}" = "y" ]; then
    if ! ${AWS} s3api create-bucket --acl private --bucket ${DEPLOYMENT_BUCKET} ${LOCATION_CONSTRAINT}; then
      exit 1
    fi
  else
    echo "Usage: bash ./scripts/deploy.sh [stack_name] [environment] [region] [deployment_bucket_name]"
    exit 1
  fi
fi

echo
echo "Press [Enter] to continue or Ctrl-C to abort."
read

# Upload required directories to Deployment S3 Bucket
for dir in artifacts api-schema knowledge-base-data-source; do
    aws s3 cp ${dir} s3://${DEPLOYMENT_BUCKET}/${dir}/ --recursive
done

###########################################################
### 3. UPDATE THE TEMPLATES WITH DEPLOYMENT BUCKET PATH ###
###########################################################

# Read the main-stack-tmp.yaml file into a variable
yml_file_contents=$(cat templates/yaml/main-stack-tmp.yaml)
# Use the sed command to replace the placeholder MyMortgageFlowBucket name with the actual deployment bucket name
updated_yml_file_contents=$(sed "s/MortgageFlowBucket/${DEPLOYMENT_BUCKET}/g"<<< "$yml_file_contents")
# Write the updated YAML file to a new file
echo "$updated_yml_file_contents" >templates/yaml/main-stack.yaml

# Read the main-stack-tmp.json file into a variable
json_file_contents=$(cat templates/json/main-stack-tmp.json)
# Use the sed command to replace the placeholder MyMortgageFlowBucket name with the actual deployment bucket name
updated_json_file_contents=$(sed "s/MortgageFlowBucket/${DEPLOYMENT_BUCKET}/g"<<< "$yml_file_contents")
# Write the updated JSON file to a new file
echo "$updated_json_file_contents" >templates/json/main-stack.json

# UPLOAD the templates to Deployment S3 Bucket
LOCAL_TEMPLATES_DIR="templates"
aws s3 cp ${LOCAL_TEMPLATES_DIR} s3://${DEPLOYMENT_BUCKET}/${LOCAL_TEMPLATES_DIR}/ --recursive

echo "Main CloudFormation template S3 URLs:"
echo "- https://${DEPLOYMENT_BUCKET}.s3.amazonaws.com/templates/yaml/main-stack.yaml"
echo "- https://${DEPLOYMENT_BUCKET}.s3.amazonaws.com/templates/json/main-stack.json"

echo "**********************************************************************************************************"
echo "All done. Now deploy the stack by specifying the S3 URL above or uploading the template."
echo "**********************************************************************************************************"
cat << __EOF__

__EOF__
