#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

# Define variables
export AWS_REGION="us-east-1"
export ECR_REPOSITORY_NAME="eks-api-gateway-demo"
export EKS_CLUSTER_NAME="eks-api-gateway-cluster"
export APP_NAME="eks-api-gateway-demo"

echo "Starting the cleanup process..."

# 1. Delete API Gateway
echo "Deleting API Gateway..."
API_ID=$(aws apigateway get-rest-apis --query "items[?name=='EKS-App-API'].id" --output text)
if [ -n "$API_ID" ]; then
    aws apigateway delete-rest-api --rest-api-id ${API_ID}
    echo "API Gateway deleted successfully."
else
    echo "API Gateway not found."
fi

# 2. Delete Ingress and Application
echo "Deleting Ingress and Application..."
kubectl delete -f ingress.yaml || echo "Ingress not found."
kubectl delete -f kubernetes-manifests.yaml || echo "Application not found."

# 3. Uninstall AWS Load Balancer Controller
echo "Uninstalling AWS Load Balancer Controller..."
helm uninstall aws-load-balancer-controller -n kube-system || echo "AWS Load Balancer Controller not found."

# 4. Delete IAM service account
export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo "Deleting IAM service account..."
eksctl delete iamserviceaccount --cluster=${EKS_CLUSTER_NAME} --namespace=kube-system --name=aws-load-balancer-controller --region ${AWS_REGION} || echo "IAM service account not found."

# 5. Delete IAM policy
echo "Deleting IAM policy..."
aws iam delete-policy --policy-arn arn:aws:iam::${AWS_ACCOUNT_ID}:policy/AWSLoadBalancerControllerIAMPolicy || echo "IAM policy not found."

# 6. Delete EKS Cluster
echo "Deleting EKS cluster... This might take a while."
eksctl delete cluster --name ${EKS_CLUSTER_NAME} --region ${AWS_REGION}

echo "EKS cluster deleted successfully."

# 7. Delete ECR Repository
echo "Deleting ECR repository..."
aws ecr delete-repository --repository-name ${ECR_REPOSITORY_NAME} --region ${AWS_REGION} --force || echo "ECR repository not found."

rm -f iam_policy.json
rm -f kubernetes-manifests.yaml.bak
rm -f ingress.yaml

echo "Cleanup complete!"
