#!/bin/sh
set -eu

if [ "$#" -lt 2 ] || [ "$#" -gt 3 ] || [ "$2" != "--confirm" ]; then
  echo "Usage: $0 EMAIL --confirm [compose|kind]" >&2
  echo "This changes exactly one existing account and only while no administrator exists." >&2
  exit 1
fi

EMAIL=$1
MODE=${3:-compose}
ENCODED_EMAIL=$(printf %s "$EMAIL" | base64 | tr -d '\n')
EXPRESSION="case Base.decode64!(\"$ENCODED_EMAIL\") |> WhoNeedHelp.Release.bootstrap_admin() do {:ok, admin} -> IO.inspect({:ok, admin}); {:error, reason} -> raise \"Admin bootstrap failed: #{inspect(reason)}\" end"

case "$MODE" in
  compose)
    TARGET=$(docker compose -p who_need_help ps -q web | head -n 1)

    if [ -z "$TARGET" ]; then
      echo "No running Compose web replica was found." >&2
      exit 1
    fi

    docker exec "$TARGET" /app/bin/who_need_help rpc "$EXPRESSION"
    ;;
  kind)
    ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
    PATH="$ROOT/.tools/bin:$PATH"
    export PATH
    TARGET=$(
      kubectl --context kind-who-need-help --namespace who-need-help get pods \
        -l app.kubernetes.io/component=web \
        -o jsonpath='{.items[0].metadata.name}'
    )

    if [ -z "$TARGET" ]; then
      echo "No running kind web replica was found." >&2
      exit 1
    fi

    kubectl --context kind-who-need-help --namespace who-need-help exec "$TARGET" -- \
      /app/bin/who_need_help rpc "$EXPRESSION"
    ;;
  *)
    echo "Mode must be compose or kind." >&2
    exit 1
    ;;
esac
