#!/bin/sh
set -eu

usage() {
  echo "usage: $0 <kubeconfig> <context> <aws-profile-or-> <region> <auth0-secret-id> [auth0-only-namespace]" >&2
  exit 2
}

[ "$#" -ge 5 ] && [ "$#" -le 6 ] || usage

kubeconfig=$1
context=$2
profile=$3
region=$4
auth0_secret_id=$5
auth0_only_namespace=${6:-}

run_kubectl() {
  KUBECONFIG="$kubeconfig" kubectl --context "$context" "$@"
}

random_hex() {
  dd if=/dev/urandom bs=32 count=1 2>/dev/null |
    od -An -tx1 |
    tr -d ' \n'
}

read_secret() {
  namespace=$1
  name=$2
  key=$3
  run_kubectl --namespace "$namespace" get secret "$name" -o json 2>/dev/null |
    jq -er --arg key "$key" '.data[$key] | @base64d' 2>/dev/null ||
    true
}

metrics_write_token=$(read_secret observability cp9-o11y-runtime metrics-write-token)
if [ -z "$metrics_write_token" ]; then
  metrics_write_token=${CP9_O11Y_METRICS_WRITE_TOKEN:-}
fi
if [ -z "$metrics_write_token" ]; then
  metrics_write_token=$(random_hex)
fi

if [ "$profile" = "-" ]; then
  auth0_secret_json=$(
    aws secretsmanager get-secret-value \
      --region "$region" \
      --secret-id "$auth0_secret_id" \
      --query SecretString \
      --output text
  )
else
  auth0_secret_json=$(
    aws --profile "$profile" secretsmanager get-secret-value \
      --region "$region" \
      --secret-id "$auth0_secret_id" \
      --query SecretString \
      --output text
  )
fi
auth0_client_id=$(printf '%s' "$auth0_secret_json" | jq -er '.Auth0ClientID')
auth0_client_secret=$(printf '%s' "$auth0_secret_json" | jq -er '.Auth0ClientSecret')

apply_auth0_client_secret() {
  namespace=$1
  AUTH0_CLIENT_ID="$auth0_client_id" \
    AUTH0_CLIENT_SECRET="$auth0_client_secret" \
    NAMESPACE="$namespace" \
    jq -n \
    '{
      apiVersion: "v1",
      kind: "Secret",
      metadata: {
        name: "o11y-auth0-client",
        namespace: env.NAMESPACE,
        labels: {"app.kubernetes.io/part-of": "cp9-o11y"}
      },
      type: "Opaque",
      stringData: {
        Auth0ClientID: env.AUTH0_CLIENT_ID,
        Auth0ClientSecret: env.AUTH0_CLIENT_SECRET
      }
    }' |
    KUBECONFIG="$kubeconfig" kubectl --context "$context" apply --server-side --force-conflicts --field-manager=cp9-o11y-runtime -f -
}

if [ -n "$auth0_only_namespace" ]; then
  apply_auth0_client_secret "$auth0_only_namespace"
  exit 0
fi

  METRICS_WRITE_TOKEN="$metrics_write_token" \
  AUTH0_CLIENT_ID="$auth0_client_id" \
  AUTH0_CLIENT_SECRET="$auth0_client_secret" \
  jq -n \
  '{
    apiVersion: "v1",
    kind: "Secret",
    metadata: {
      name: "cp9-o11y-runtime",
      namespace: "observability",
      labels: {"app.kubernetes.io/part-of": "cp9-o11y"}
    },
    type: "Opaque",
    stringData: {
      "metrics-write-token": env.METRICS_WRITE_TOKEN,
      "auth0-client-id": env.AUTH0_CLIENT_ID,
      "auth0-client-secret": env.AUTH0_CLIENT_SECRET
    }
  }' |
  KUBECONFIG="$kubeconfig" kubectl --context "$context" apply --server-side --force-conflicts --field-manager=cp9-o11y-runtime -f -

for namespace in cp9-premium cp9-dedicated; do
  apply_auth0_client_secret "$namespace"
done

METRICS_WRITE_TOKEN="$metrics_write_token" jq -n \
  '{
    apiVersion: "v1",
    kind: "Secret",
    metadata: {
      name: "cp9-o11y-kong-key",
      namespace: "observability",
      labels: {"konghq.com/credential": "key-auth"}
    },
    type: "Opaque",
    stringData: {
      key: env.METRICS_WRITE_TOKEN
    }
  }' |
  KUBECONFIG="$kubeconfig" kubectl --context "$context" apply --server-side --force-conflicts --field-manager=cp9-o11y-runtime -f -

METRICS_WRITE_TOKEN="$metrics_write_token" jq -n \
  '{
    apiVersion: "v1",
    kind: "Secret",
    metadata: {
      name: "cp9-o11y-kong-bearer-key",
      namespace: "observability",
      labels: {"konghq.com/credential": "key-auth"}
    },
    type: "Opaque",
    stringData: {
      key: ("Bearer " + env.METRICS_WRITE_TOKEN)
    }
  }' |
  KUBECONFIG="$kubeconfig" kubectl --context "$context" apply --server-side --force-conflicts --field-manager=cp9-o11y-runtime -f -
