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

: "${LAYERBASE_API_KEY:?Set LAYERBASE_API_KEY to your Layerbase API key.}"
: "${LAYERBASE_DATABASE_ID:?Set LAYERBASE_DATABASE_ID to the database ID.}"

LAYERBASE_API_URL="${LAYERBASE_API_URL:-https://cloud.layerbase.dev}"
LAYERBASE_FIREWALL_LABEL="${LAYERBASE_FIREWALL_LABEL:-Dynamic egress}"
LAYERBASE_API_URL="${LAYERBASE_API_URL%/}"

command -v curl >/dev/null 2>&1 || {
  echo "curl is required." >&2
  exit 1
}
command -v jq >/dev/null 2>&1 || {
  echo "jq is required." >&2
  exit 1
}

authorization_header="Authorization: Bearer ${LAYERBASE_API_KEY}"
firewall_url="${LAYERBASE_API_URL}/v1/databases/${LAYERBASE_DATABASE_ID}/firewall"

current_ip="$(
  curl --fail-with-body --silent --show-error \
    --header "${authorization_header}" \
    "${LAYERBASE_API_URL}/v1/ip" |
    jq --exit-status --raw-output '.ip | select(type == "string" and length > 0)'
)"

firewall_state="$(
  curl --fail-with-body --silent --show-error \
    --header "${authorization_header}" \
    "${firewall_url}"
)"

if jq --exit-status --arg ip "${current_ip}" \
  '.allowlist[]? | select(.ip == $ip)' \
  >/dev/null <<<"${firewall_state}"; then
  echo "Current egress IP ${current_ip} is already allowed."
  exit 0
fi

payload="$(
  jq --null-input --compact-output \
    --arg ip "${current_ip}" \
    --arg label "${LAYERBASE_FIREWALL_LABEL}" \
    '{ ip: $ip, label: $label }'
)"

if add_response="$(
  curl --fail-with-body --silent --show-error \
    --request POST \
    --header "${authorization_header}" \
    --header "Content-Type: application/json" \
    --data "${payload}" \
    "${firewall_url}/allow"
)"; then
  jq . <<<"${add_response}"
else
  # Concurrent cold starts can both observe the IP as absent before one wins
  # the POST. Re-read after any failed add: if the desired IP now exists, the
  # operation converged and is an idempotent success. Otherwise fail normally.
  refreshed_state="$(
    curl --fail-with-body --silent --show-error \
      --header "${authorization_header}" \
      "${firewall_url}"
  )"
  if jq --exit-status --arg ip "${current_ip}" \
    '.allowlist[]? | select(.ip == $ip)' \
    >/dev/null <<<"${refreshed_state}"; then
    echo "Current egress IP ${current_ip} was allowed concurrently."
    exit 0
  fi
  echo "Failed to add current egress IP ${current_ip}." >&2
  exit 1
fi

if ! jq --exit-status '.ipRestricted == true' >/dev/null <<<"${firewall_state}"; then
  echo "Added ${current_ip}, but IP restrictions are currently disabled."
  echo "Enable them separately after confirming every required source is allowed."
else
  echo "Added current egress IP ${current_ip}."
fi
