#!/bin/bash
set -e

contains_prefix() {
  local prefix=$1       # The prefix to search for (e.g., "backend")
  shift                 # Remove the prefix argument
  local tags=("$@")     # Remaining arguments are the tags array

  # Use grep to check if any tag starts with the prefix
  if printf '%s\n' "${tags[@]}" | grep -q "^${prefix}"; then
    return 0
  else
    return 1
  fi
}

ec2Instance=ubuntu@ec2-3-125-141-157.eu-central-1.compute.amazonaws.com

# Find new tags since last pipeline run
newTags=($(git tag --contains $NX_BASE))

if ((${#newTags[@]} == 0)); then
	echo "Skipping deployment because no new tags were found"
	exit 0
fi

echo New Tags:$'\n'${newTags[@]}$'\n'


# Backend
if contains_prefix "backend" "${newTags[@]}"; then
	echo "Deploying backend"

	repositoryUrl=903393797582.dkr.ecr.eu-central-1.amazonaws.com/backend-production
	clusterName=backend-production

	# Login to AWS ECR and save docker credentials
	aws ecr get-login-password --region eu-central-1 | docker login --username AWS --password-stdin $repositoryUrl

	# Find latest git tag for backend and use it as image tag
	imageTag=$(git tag --sort -v:refname | grep -xe "backend.*" | grep -oe '\([0-9.]*\)' | sed -n '1p')
	echo "Latest git tag for backend is $imageTag"

	docker tag backend:latest $repositoryUrl:$imageTag
	docker tag backend:latest $repositoryUrl:latest

	docker push $repositoryUrl:$imageTag
	docker push $repositoryUrl:latest

	# Force deployment of ECS service
	aws ecs update-service --region eu-central-1 --cluster $clusterName --service backend --force-new-deployment --no-cli-pager
fi

# Create EC2 SSH key
echo "$STATIC_WEB_SERVER_SSH_KEY" >private_key && chmod 600 private_key

# Admin Web
if contains_prefix "admin-web" "${newTags[@]}"; then
	echo "Deploying admin-web"

	scp -o StrictHostKeyChecking=no -i private_key -r dist/apps/admin/web/* $ec2Instance:/var/www/html/admin-web-production/
fi

# Customer
if contains_prefix "customer" "${newTags[@]}"; then
	echo "Deploying customer"

	scp -o StrictHostKeyChecking=no -i private_key -r dist/apps/customer/* $ec2Instance:/var/www/html/customer-production/
fi

# Reservation Widget
if contains_prefix "reservation-widget" "${newTags[@]}"; then
	echo "Deploying reservation-widget"

	# Find latest git tag for reservation-widget and use it as directory name
	directoryName=$(git tag --sort -v:refname | grep -xe "reservation-widget.*" | grep -oe '\([0-9.]*\)' | sed -n '1p')
	echo "Latest git tag for reservation-widget is $directoryName"

	# Upload to S3
	aws s3 cp "dist/apps/reservation-widget/element" "s3://kadi-static/reservation-widget/production/$directoryName" --acl "public-read" --recursive
	aws s3 cp "dist/apps/reservation-widget/element" "s3://kadi-static/reservation-widget/production" --acl "public-read" --recursive

	# Invalidate CloudFront cache for reservation widget
	echo "Invalidating CloudFront cache for reservation-widget"
	DISTRIBUTION_ID=$(aws cloudfront list-distributions \
		--query "DistributionList.Items[?Origins.Items[?OriginPath=='/reservation-widget']].Id" \
		--output text)

	if [ -n "$DISTRIBUTION_ID" ]; then
		aws cloudfront create-invalidation \
			--distribution-id "$DISTRIBUTION_ID" \
			--paths "/production/*" \
			--no-cli-pager
	else
		echo "Warning: Could not find CloudFront distribution for reservation-widget"
	fi
fi

# Delete EC2 SSH key
rm -f private_key

exit 0
