#!/bin/sh
set -eu

usage() {
  echo "usage: $0 <kubeconfig> <context> <sql-path>" >&2
  exit 2
}

[ "$#" -eq 3 ] || usage

kubeconfig=$1
context=$2
sql_path=$3

if [ ! -s "$sql_path" ]; then
  echo "Dedicated Global Service seed SQL not found: $sql_path" >&2
  exit 1
fi

sql_input=$sql_path
if grep -q '__CP9_GCP_REGIONAL_ENDPOINT_URL__' "$sql_path"; then
  endpoint=${CP9_GCP_REGIONAL_ENDPOINT_URL:-}
  case "$endpoint" in
    https://*) endpoint_host=${endpoint#https://} ;;
    *)
      echo "CP9_GCP_REGIONAL_ENDPOINT_URL must be an HTTPS URL" >&2
      exit 1
      ;;
  esac
  case "$endpoint_host" in
    ''|*[!A-Za-z0-9.-]*)
      echo "CP9_GCP_REGIONAL_ENDPOINT_URL must contain only a DNS host" >&2
      exit 1
      ;;
  esac
  sql_input=$(mktemp)
  trap 'rm -f "$sql_input"' EXIT
  sed "s|__CP9_GCP_REGIONAL_ENDPOINT_URL__|$endpoint|g" "$sql_path" >"$sql_input"
fi

for _ in $(seq 1 120); do
  if KUBECONFIG="$kubeconfig" kubectl --context "$context" --namespace cp9-system \
    exec -i deploy/premium-metadb -- env MYSQL_PWD=cp9-local \
    mysql -h 127.0.0.1 -uroot <"$sql_input"; then
    exit 0
  fi
  sleep 2
done

echo "Timed out applying dedicated_global_service database seed" >&2
exit 1
