#!/usr/bin/env bash
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
module_dir="${TF_MODULE_DIR:-$(cd "$script_dir/.." && pwd)}"

profile="$(terraform -chdir="$module_dir" output -raw aws_profile)"
region="$(terraform -chdir="$module_dir" output -raw aws_region)"
service_ids_json="$(terraform -chdir="$module_dir" output -json privatelink_service_ids)"

mapfile -t service_ids < <(jq -r '.[] | select(. != null and . != "")' <<<"$service_ids_json")
if ((${#service_ids[@]} == 0)); then
  exit 0
fi

blocked=0
for service_id in "${service_ids[@]}"; do
  connections="$(aws ec2 describe-vpc-endpoint-connections \
    --profile "$profile" \
    --region "$region" \
    --filters "Name=service-id,Values=$service_id" \
    --output json)"
  active="$(jq -r '.VpcEndpointConnections[]? | select(.VpcEndpointState == "available" or .VpcEndpointState == "pendingAcceptance") | [.VpcEndpointId, .VpcEndpointState] | @tsv' <<<"$connections")"
  if [[ -n "$active" ]]; then
    echo "Endpoint service $service_id still has active consumer endpoints:" >&2
    echo "$active" >&2
    blocked=1
  fi
done

if ((blocked)); then
  echo "Delete the listed consumer endpoints before deep sleep." >&2
  exit 1
fi
