#!/bin/bash
set -e

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

# True in last pipe prevents returning an error when no match is found
affected=($(pnpm nx show projects --affected --select=projects --type=app --base=$NX_BASE --head=$NX_HEAD | grep -v -x -e ">.*" | { grep -v -e "^$" || true; }))

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

echo Affected Projects:$'\n'${affected[@]}$'\n'

latestGitCommit=$(echo $NX_HEAD | head -c 7)

# Backend
if [[ " ${affected[*]} " =~ "backend" ]]; then
	echo "Deploying backend"

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

	# 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 appended with git commit sha
	# e.g 0.2.0-83d57ba
	latestGitTag=$(git tag --sort -v:refname | grep -xe "backend.*" | grep -oe '\([0-9.]*\)' | sed -n '1p')
	imageTag=$latestGitTag-$latestGitCommit
	echo "Latest git tag for backend is $latestGitTag, tagging image as $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 [[ " ${affected[*]} " =~ "admin-web" ]]; then
	echo "Deploying admin-web"

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

# Customer Client
if [[ " ${affected[*]} " =~ "customer" ]]; then
	echo "Deploying customer"

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

# Reservation Widget
if [[ " ${affected[*]} " =~ "reservation-widget" ]]; then
	echo "Deploying reservation-widget"

	# Find latest git tag for reservation-widget and use it as directory name appended with git commit sha
	# e.g 0.2.0-83d57ba
	latestGitTag=$(git tag --sort -v:refname | grep -xe "reservation-widget.*" | grep -oe '\([0-9.]*\)' | sed -n '1p')
	directoryName=$latestGitTag-$latestGitCommit
	echo "Latest git tag for reservation-widget is $latestGitTag, will be uploaded to $directoryName"

	# Upload to S3
	aws s3 cp "dist/apps/reservation-widget/element" "s3://kadi-static/reservation-widget/staging/$directoryName" --acl "public-read" --recursive
	aws s3 cp "dist/apps/reservation-widget/element" "s3://kadi-static/reservation-widget/staging" --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 "/staging/*" \
			--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
