---
apiVersion: v1
kind: ConfigMap
metadata:
  name: jupyterhub-config-job
  namespace: keycloak
data:
  jupyterhub-client-payload.json: |
    {
      "protocol": "openid-connect",
      "clientId": "jupyterhub",
      "name": "Jupyterhub Client",
      "description": "Used for Jupyterhub SSO",
      "publicClient": false,
      "authorizationServicesEnabled": false,
      "serviceAccountsEnabled": false,
      "implicitFlowEnabled": false,
      "directAccessGrantsEnabled": true,
      "standardFlowEnabled": true,
      "frontchannelLogout": true,
      "attributes": {
        "saml_idp_initiated_sso_url_name": "",
        "oauth2.device.authorization.grant.enabled": false,
        "oidc.ciba.grant.enabled": false
      },
      "alwaysDisplayInConsole": false,
      "rootUrl": "",
      "baseUrl": "",
      "redirectUris": [
        "https://cnoe.localtest.me:8443/jupyterhub/hub/oauth_callback"
      ],
      "webOrigins": [
        "/*"
      ]
    }
---
apiVersion: batch/v1
kind: Job
metadata:
  name: jupyterhub-config
  namespace: keycloak
spec:
  template:
    metadata:
      generateName: jupyterhub-config
    spec:
      serviceAccountName: keycloak-config
      restartPolicy: Never
      volumes:
        - name: keycloak-config
          secret:
            secretName: keycloak-config
        - name: config-payloads
          configMap:
            name: jupyterhub-config-job
      containers:
        - name: kubectl
          image: docker.io/library/ubuntu:22.04
          volumeMounts:
            - name: keycloak-config
              readOnly: true
              mountPath: "/var/secrets/"
            - name: config-payloads
              readOnly: true
              mountPath: "/var/config/"
          command: ["/bin/bash", "-c"]
          args:
            - |
              #! /bin/bash
              set -ex -o pipefail
              apt -qq update && apt -qq install curl jq gettext-base -y
              
              curl -sS -LO "https://dl.k8s.io/release/v1.28.3//bin/linux/amd64/kubectl"
              chmod +x kubectl
              
              echo "checking if we're ready to start"
              set +e
              ./kubectl get secret -n keycloak keycloak-clients &> /dev/null
              if [ $? -ne 0 ]; then
                exit 1
              fi
              set -e
              
              ADMIN_PASSWORD=$(cat /var/secrets/KEYCLOAK_ADMIN_PASSWORD)
              KEYCLOAK_URL=http://keycloak.keycloak.svc.cluster.local:8080/keycloak
              KEYCLOAK_TOKEN=$(curl -sS  --fail-with-body -X POST -H "Content-Type: application/x-www-form-urlencoded" \
                --data-urlencode "username=cnoe-admin" \
                --data-urlencode "password=${ADMIN_PASSWORD}" \
                --data-urlencode "grant_type=password" \
                --data-urlencode "client_id=admin-cli" \
                ${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token | jq -e -r '.access_token')
              
              set +e
              
              curl --fail-with-body -H "Authorization: bearer ${KEYCLOAK_TOKEN}"  "${KEYCLOAK_URL}/admin/realms/cnoe"  &> /dev/null
              if [ $? -ne 0 ]; then
                exit 0
              fi
              set -e
              
              echo "creating Jupyterhub client"
              curl -sS -H "Content-Type: application/json" \
                -H "Authorization: bearer ${KEYCLOAK_TOKEN}" \
                -X POST --data @/var/config/jupyterhub-client-payload.json \
                  ${KEYCLOAK_URL}/admin/realms/cnoe/clients
              
              CLIENT_ID=$(curl -sS -H "Content-Type: application/json" \
                -H "Authorization: bearer ${KEYCLOAK_TOKEN}" \
                -X GET ${KEYCLOAK_URL}/admin/realms/cnoe/clients | jq -e -r  '.[] | select(.clientId == "jupyterhub") | .id')
              
              CLIENT_SCOPE_GROUPS_ID=$(curl -sS -H "Content-Type: application/json" -H "Authorization: bearer ${KEYCLOAK_TOKEN}" -X GET  ${KEYCLOAK_URL}/admin/realms/cnoe/client-scopes | jq -e -r  '.[] | select(.name == "groups") | .id')
              curl -sS -H "Content-Type: application/json" -H "Authorization: bearer ${KEYCLOAK_TOKEN}" -X PUT  ${KEYCLOAK_URL}/admin/realms/cnoe/clients/${CLIENT_ID}/default-client-scopes/${CLIENT_SCOPE_GROUPS_ID}
              
              JUPYTERHUB_CLIENT_SECRET=$(curl -sS -H "Content-Type: application/json" \
                -H "Authorization: bearer ${KEYCLOAK_TOKEN}" \
                -X GET ${KEYCLOAK_URL}/admin/realms/cnoe/clients/${CLIENT_ID} | jq -e -r '.secret')
              
              ./kubectl patch secret -n keycloak keycloak-clients --type=json \
                -p='[{
                "op" : "add" ,
                "path" : "/data/JUPYTERHUB_CLIENT_SECRET" ,
                "value" : "'$(echo -n "$JUPYTERHUB_CLIENT_SECRET" | base64 -w 0)'"
                },{
                  "op" : "add" ,
                  "path" : "/data/JUPYTERHUB_CLIENT_ID" ,
                  "value" : "'$(echo -n "jupyterhub" | base64 -w 0)'"
                }]'
