#!/bin/bash
set -e # Exit immediately if any command fails

# 1. AWS credentials from environment variables
if [[ -n "${AWS_ACCESS_KEY_ID}" && -n "${AWS_SECRET_ACCESS_KEY}" ]]; then
    echo "Using AWS credentials from environment variables."
else
    # 2. AWS credentials from params.aws in the template
    {% if params.aws.access_key and params.aws.secret_access_key %}
    export AWS_ACCESS_KEY_ID="{{ params.aws.access_key }}"
    export AWS_SECRET_ACCESS_KEY="{{ params.aws.secret_access_key }}"
    
    {% if params.aws.session_token %}
    export AWS_SESSION_TOKEN="{{ params.aws.session_token }}"
    {% endif %}
    
    echo "Using AWS credentials from params.aws in template."
    
    {% else %}
    # 3. Use AWS_PROFILE if defined, otherwise default to the profile set in AWS CLI
    {% if params.aws.profile %}
    export AWS_PROFILE="{{ params.aws.profile }}"
    echo "Using AWS profile: ${AWS_PROFILE}"
    {% else %}
    echo "Using default AWS profile."
    {% endif %}
    
    {% endif %}
fi

# Set AWS region: Check params.region first, then params.aws.region, and finally use a default value
AWS_REGION="{{ params.region | default(params.aws.region | default('eu-west-1')) }}"

# Dynamically get AWS account ID using the credentials
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' --output text 2> /dev/null)
if [ $? -ne 0 ]; then
    echo "Error: AWS credentials or token are expired or invalid. Please renew your session or re-authenticate."
    exit 1
fi

# Check if AWS_ACCOUNT_ID is empty
if [ -z "${AWS_ACCOUNT_ID}" ]; then
    echo "Error: Failed to retrieve AWS account ID. Please check your AWS credentials."
    exit 1
fi

# Image name in ECR format
IMAGE_NAME="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/{{ params.image_name }}"

# Generate image tag, typically using the version or a timestamp
IMAGE_TAG="{{ params.version }}"

# Build arguments
BUILD_ARGS=""

{% if config.env %}
# Add build arguments from config.env
{% for key, value in config.env %}
BUILD_ARGS="$BUILD_ARGS --build-arg {{ key }}='{{ value }}'"
{% endfor %}
{% endif %}

{% if params.env %}
# Add build arguments from params.env
{% for key, value in params.env %}
BUILD_ARGS="$BUILD_ARGS --build-arg {{ key }}='{{ value }}'"
{% endfor %}
{% endif %}

{% if config.args %}
# Add build arguments from config.args
{% for key, value in config.args %}
BUILD_ARGS="$BUILD_ARGS --build-arg {{ key }}='{{ value }}'"
{% endfor %}
{% endif %}

{% if params.args %}
# Add build arguments from params.args
{% for key, value in params.args %}
BUILD_ARGS="$BUILD_ARGS --build-arg {{ key }}='{{ value }}'"
{% endfor %}
{% endif %}

# Builder name
BUILDER_NAME="multi-arch-builder"

# Check if the builder already exists
if ! docker buildx inspect $BUILDER_NAME > /dev/null 2>&1; then
    # Create a new Docker Buildx builder instance if it does not exist
    docker buildx create --name $BUILDER_NAME --use
else
    # Use the existing builder
    docker buildx use $BUILDER_NAME
fi

# Start up the builder instance
docker buildx inspect --bootstrap

# Authenticate Docker to ECR using the AWS profile or credentials
aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com
if [ $? -ne 0 ]; then
    echo "Error: Failed to login to AWS ECR. Please check your credentials."
    exit 1
fi

# Ensure the repository exists in ECR, create it if not
aws ecr describe-repositories --repository-names "{{ params.image_name }}" --region ${AWS_REGION} > /dev/null 2>&1 || \
    aws ecr create-repository --repository-name "{{ params.image_name }}" --region ${AWS_REGION}
if [ $? -ne 0 ]; then
    echo "Error: Failed to create or describe the repository. Please check your permissions."
    exit 1
fi

# Build and push the image for multiple platforms
{% if params.push == true %}
docker buildx build --platform linux/arm64,linux/amd64 $BUILD_ARGS -t ${IMAGE_NAME}:latest -t ${IMAGE_NAME}:${IMAGE_TAG} --push .
if [ $? -ne 0 ]; then
    echo "Error: Docker push failed."
    exit 1
fi
{% else %}
docker buildx build --platform linux/arm64,linux/amd64 $BUILD_ARGS -t ${IMAGE_NAME}:latest -t ${IMAGE_NAME}:${IMAGE_TAG} .
if [ $? -ne 0 ]; then
    echo "Error: Docker build failed."
    exit 1
fi
{% endif %}