apiVersion: batch/v1
kind: Job
metadata:
  name: keycloak-bootstrap-realm
  namespace: keycloak
  labels:
    app.kubernetes.io/name: keycloak-bootstrap-realm
    hwlab.pikastech.local/component: identity
spec:
  backoffLimit: 1
  activeDeadlineSeconds: 600
  template:
    metadata:
      labels:
        app.kubernetes.io/name: keycloak-bootstrap-realm
        hwlab.pikastech.local/component: identity
    spec:
      restartPolicy: Never
      initContainers:
        - name: wait-for-keycloak
          image: curlimages/curl:8.10.1
          command:
            - /bin/sh
            - -c
            - |
              set -eu
              KC=http://keycloak.keycloak.svc.cluster.local:8080
              for i in $(seq 1 60); do
                code=$(curl -s -o /dev/null -w '%{http_code}' $KC/realms/master || true)
                code=${code:-000}
                if [ "$code" = "200" ]; then
                  echo keycloak-ready
                  exit 0
                fi
                echo "waiting-for-keycloak status=$code"
                sleep 5
              done
              echo keycloak-not-ready
              exit 1
      containers:
        - name: bootstrap
          image: quay.io/keycloak/keycloak:25.0
          env:
            - name: PASSWORD
              valueFrom:
                secretKeyRef:
                  name: keycloak-admin
                  key: password
            - name: CLIENT_SECRET
              valueFrom:
                secretKeyRef:
                  name: hwlab-cloud-web-client
                  key: client-secret
            - name: KEYCLOAK_BASE_URL
              value: http://keycloak.keycloak.svc.cluster.local:8080
            - name: REALM
              value: hwlab
            - name: CLIENT_ID
              value: hwlab-cloud-web
            - name: REDIRECT_URI_DEV
              value: https://hwlab.74-48-78-17.nip.io/auth/oidc/callback
            - name: WEB_ORIGIN_DEV
              value: https://hwlab.74-48-78-17.nip.io
            - name: ACCESS_TOKEN_LIFESPAN
              value: "1440"
            - name: SSO_SESSION_MAX_LIFESPAN
              value: "86400"
          command:
            - /bin/sh
            - -c
            - |
              set -eu
              KC="$KEYCLOAK_BASE_URL"
              KCADM=/opt/keycloak/bin/kcadm.sh
              CONFIG=/tmp/kcadm.config
              echo "fetching-admin-token"
              "$KCADM" config credentials \
                --config "$CONFIG" \
                --server "$KC" \
                --realm master \
                --user admin \
                --password "$PASSWORD" \
                --client admin-cli >/tmp/kcadm-login.log
              echo "token-ok"
              if "$KCADM" get "realms/$REALM" --config "$CONFIG" >/tmp/realm.json 2>/tmp/realm.err; then
                echo "realm-already-exists"
                "$KCADM" update "realms/$REALM" \
                  --config "$CONFIG" \
                  -s enabled=true \
                  -s registrationAllowed=true \
                  -s verifyEmail=false \
                  -s loginWithEmailAllowed=true \
                  -s duplicateEmailsAllowed=false \
                  -s resetPasswordAllowed=false \
                  -s editUsernameAllowed=false \
                  -s bruteForceProtected=false \
                  -s accessTokenLifespan="$ACCESS_TOKEN_LIFESPAN" \
                  -s ssoSessionIdleTimeout="$SSO_SESSION_MAX_LIFESPAN" \
                  -s ssoSessionMaxLifespan="$SSO_SESSION_MAX_LIFESPAN"
                echo "realm-updated"
              else
                echo "creating-realm"
                "$KCADM" create realms \
                  --config "$CONFIG" \
                  -s realm="$REALM" \
                  -s enabled=true \
                  -s registrationAllowed=true \
                  -s verifyEmail=false \
                  -s loginWithEmailAllowed=true \
                  -s duplicateEmailsAllowed=false \
                  -s resetPasswordAllowed=false \
                  -s editUsernameAllowed=false \
                  -s bruteForceProtected=false \
                  -s accessTokenLifespan="$ACCESS_TOKEN_LIFESPAN" \
                  -s ssoSessionIdleTimeout="$SSO_SESSION_MAX_LIFESPAN" \
                  -s ssoSessionMaxLifespan="$SSO_SESSION_MAX_LIFESPAN"
                echo "realm-created"
              fi
              CLIENT_UUID=$("$KCADM" get clients \
                --config "$CONFIG" \
                -r "$REALM" \
                -q clientId="$CLIENT_ID" \
                --fields id \
                --format csv \
                --noquotes | head -1 | tr -d '\r')
              if [ -n "$CLIENT_UUID" ]; then
                echo "client-already-exists"
                "$KCADM" update "clients/$CLIENT_UUID" \
                  --config "$CONFIG" \
                  -r "$REALM" \
                  -s clientId="$CLIENT_ID" \
                  -s secret="$CLIENT_SECRET" \
                  -s 'redirectUris=["'"$REDIRECT_URI_DEV"'"]' \
                  -s 'webOrigins=["'"$WEB_ORIGIN_DEV"'"]' \
                  -s standardFlowEnabled=true \
                  -s directAccessGrantsEnabled=false
                echo "client-updated"
              else
                echo "creating-client"
                "$KCADM" create clients \
                  --config "$CONFIG" \
                  -r "$REALM" \
                  -s clientId="$CLIENT_ID" \
                  -s secret="$CLIENT_SECRET" \
                  -s 'redirectUris=["'"$REDIRECT_URI_DEV"'"]' \
                  -s 'webOrigins=["'"$WEB_ORIGIN_DEV"'"]' \
                  -s standardFlowEnabled=true \
                  -s directAccessGrantsEnabled=false
                echo "client-created"
              fi
              echo "keycloak-bootstrap-complete"
