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

privatelink="$(terraform output -json privatelink)"
project_id="$(terraform output -raw gcp_project_id)"
region="$(terraform output -raw gcp_region)"
if [[ "$(jq -r '.enabled' <<<"$privatelink")" != "true" ]]; then
  exit 0
fi

blocked=0
while IFS= read -r attachment; do
  endpoints="$(gcloud compute service-attachments describe "$attachment" \
    --project "$project_id" \
    --region "$region" \
    --format='value(connectedEndpoints[].endpoint)')"
  if [[ -n "$endpoints" ]]; then
    printf '%s\n' "$endpoints" >&2
    blocked=1
  fi
done < <(jq -r '[.mysql.service_attachment, .kafka.service_attachment] | unique[]' <<<"$privatelink")

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