#!/bin/bash
source "$ROOT_PATH"/scripts/common.sh
set -eo pipefail

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

# Define variables
file_name="$VERSION_TO_DEPLOY-$LAMBDA_NAME.zip"

if [[ "$ENV_NAME" == "production" && "$AWS_REGION" == "eu-west-1" ]]; then
    s3_bucket="qsase-prod-eu-env-files"
else
    s3_bucket="p81-$ENV_NAME-env-files"
fi

# Removing old packages from S3
echo_red "Removing old packages from S3..."
aws s3 rm --recursive --exclude "*" --include "*$LAMBDA_NAME.zip" s3://$s3_bucket/zips/ || handle_error "Failed to remove old lambda package from S3."

# Upload the lambda to S3
echo_red "Uploading the lambda to S3..."
aws s3 cp lambda.zip "s3://$s3_bucket/zips/$file_name" || handle_error "Failed to upload lambda to S3."

echo_green "Upload was successful!"

# Tag the zip package on S3
aws s3api put-object-tagging --bucket $s3_bucket --key "zips/$file_name" --tagging "TagSet=[{Key=LAMBDA_VERSION,Value=$VERSION_TO_DEPLOY}]" || handle_error "Failed to tag zip package on S3."

echo_green "Tagging the zip package was successful!"
