---
apiVersion: v1
data:
  generate-secrets.sh: |
    set -e

    generate_secret() {
        openssl rand -hex 16 | tr 'a-f' 'A-F' | head -c 32
    }

    AIRM_UI_SECRET=$(generate_secret)
    AIRM_ADMIN_SECRET=$(generate_secret)
    AIRM_CI_SECRET=$(generate_secret)
    AIRM_UI_NEXTAUTH_SECRET=$(generate_secret)
    KC_SUPERUSER_USERNAME=$(generate_secret)
    KC_SUPERUSER_PASSWORD=$(generate_secret)
    K8S_CLIENT_SECRET=$(generate_secret)

    cat > /tmp/final-secret-store.yaml << EOF
    apiVersion: external-secrets.io/v1beta1
    kind: ClusterSecretStore
    metadata:
      name: keycloak-secret-store
    spec:
      provider:
        fake:
          data:
          - key: keycloak_initial_admin_password
            value: admin
          - key: keycloak-cnpg-user-username
            value: keycloak
          - key: keycloak-cnpg-user-password
            value: keycloak
          - key: keycloak-cnpg-superuser-username
            value: ${KC_SUPERUSER_USERNAME}
          - key: keycloak-cnpg-superuser-password
            value: ${KC_SUPERUSER_PASSWORD}
          - key: airm-ui-keycloak-secret
            value: ${AIRM_UI_SECRET}
          - key: airm-legacy-auth-nextauth-secret
            value: ${AIRM_UI_NEXTAUTH_SECRET}
          - key: airm-keycloak-admin-client-id
            value: 'admin-client-id-value'
          - key: airm-keycloak-k8s-client-secret
            value: ${K8S_CLIENT_SECRET}
          - key: airm-keycloak-admin-client-secret
            value: ${AIRM_ADMIN_SECRET}
          - key: airm-ci-client-secret
            value: ${AIRM_CI_SECRET}
    EOF


    if kubectl get clustersecretstores.external-secrets.io keycloak-secret-store >/dev/null 2>&1; then
      echo "ClusterSecretStore 'keycloak-secret-store' already exists, skipping creation."
      exit 0
    fi

    echo "ClusterSecretStore does not exist, creating it..."
    kubectl apply -f /tmp/final-secret-store.yaml
    echo "ClusterSecretStore 'keycloak-secret-store' created successfully!"

    echo "Generated secrets with alphanumeric values only"
    exit 0
kind: ConfigMap
metadata:
  name: keycloak-secret-generator-script
  namespace: keycloak
