# services/comms/seed-othrys-room.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: seed-othrys-room
  namespace: comms
  labels:
    atlas.bstein.dev/glue: "true"
spec:
  schedule: "*/10 * * * *"
  suspend: true
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      backoffLimit: 0
      template:
        metadata:
          annotations:
            vault.hashicorp.com/agent-inject: "true"
            vault.hashicorp.com/agent-pre-populate-only: "true"
            vault.hashicorp.com/role: "comms"
            vault.hashicorp.com/agent-inject-secret-turn-secret: "kv/data/atlas/comms/turn-shared-secret"
            vault.hashicorp.com/agent-inject-template-turn-secret: |
              {{- with secret "kv/data/atlas/comms/turn-shared-secret" -}}{{ .Data.data.TURN_STATIC_AUTH_SECRET }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-livekit-primary: "kv/data/atlas/comms/livekit-api"
            vault.hashicorp.com/agent-inject-template-livekit-primary: |
              {{- with secret "kv/data/atlas/comms/livekit-api" -}}{{ .Data.data.primary }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-bot-pass: "kv/data/atlas/comms/atlasbot-credentials-runtime"
            vault.hashicorp.com/agent-inject-template-bot-pass: |
              {{- with secret "kv/data/atlas/comms/atlasbot-credentials-runtime" -}}{{ index .Data.data "bot-password" }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-seeder-pass: "kv/data/atlas/comms/atlasbot-credentials-runtime"
            vault.hashicorp.com/agent-inject-template-seeder-pass: |
              {{- with secret "kv/data/atlas/comms/atlasbot-credentials-runtime" -}}{{ index .Data.data "seeder-password" }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-chat-matrix: "kv/data/atlas/shared/chat-ai-keys-runtime"
            vault.hashicorp.com/agent-inject-template-chat-matrix: |
              {{- with secret "kv/data/atlas/shared/chat-ai-keys-runtime" -}}{{ .Data.data.matrix }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-chat-homepage: "kv/data/atlas/shared/chat-ai-keys-runtime"
            vault.hashicorp.com/agent-inject-template-chat-homepage: |
              {{- with secret "kv/data/atlas/shared/chat-ai-keys-runtime" -}}{{ .Data.data.homepage }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-mas-admin-secret: "kv/data/atlas/comms/mas-admin-client-runtime"
            vault.hashicorp.com/agent-inject-template-mas-admin-secret: |
              {{- with secret "kv/data/atlas/comms/mas-admin-client-runtime" -}}{{ .Data.data.client_secret }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-synapse-db-pass: "kv/data/atlas/comms/synapse-db"
            vault.hashicorp.com/agent-inject-template-synapse-db-pass: |
              {{- with secret "kv/data/atlas/comms/synapse-db" -}}{{ .Data.data.POSTGRES_PASSWORD }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-mas-db-pass: "kv/data/atlas/comms/mas-db"
            vault.hashicorp.com/agent-inject-template-mas-db-pass: |
              {{- with secret "kv/data/atlas/comms/mas-db" -}}{{ .Data.data.password }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-mas-matrix-shared: "kv/data/atlas/comms/mas-secrets-runtime"
            vault.hashicorp.com/agent-inject-template-mas-matrix-shared: |
              {{- with secret "kv/data/atlas/comms/mas-secrets-runtime" -}}{{ .Data.data.matrix_shared_secret }}{{- end -}}
            vault.hashicorp.com/agent-inject-secret-mas-kc-secret: "kv/data/atlas/comms/mas-secrets-runtime"
            vault.hashicorp.com/agent-inject-template-mas-kc-secret: |
              {{- with secret "kv/data/atlas/comms/mas-secrets-runtime" -}}{{ .Data.data.keycloak_client_secret }}{{- end -}}
        spec:
          restartPolicy: Never
          serviceAccountName: comms-vault
          containers:
            - name: seed
              image: python:3.11-slim
              env:
                - name: SYNAPSE_BASE
                  value: http://othrys-synapse-matrix-synapse:8008
                - name: AUTH_BASE
                  value: http://matrix-authentication-service:8080
                - name: SEEDER_USER
                  value: othrys-seeder
                - name: BOT_USER
                  value: atlasbot
              command:
                - /bin/sh
                - -c
                - |
                  set -euo pipefail
                  . /vault/scripts/comms_vault_env.sh
                  pip install --no-cache-dir requests pyyaml >/dev/null
                  python - <<'PY'
                  import os, requests, urllib.parse

                  BASE = os.environ["SYNAPSE_BASE"]
                  AUTH_BASE = os.environ.get("AUTH_BASE", BASE)

                  def canon_user(user):
                      u = (user or "").strip()
                      if u.startswith("@") and ":" in u:
                          return u
                      u = u.lstrip("@")
                      if ":" in u:
                          return f"@{u}"
                      return f"@{u}:live.bstein.dev"

                  def login(user, password):
                      r = requests.post(f"{AUTH_BASE}/_matrix/client/v3/login", json={
                          "type": "m.login.password",
                          "identifier": {"type": "m.id.user", "user": canon_user(user)},
                          "password": password,
                      })
                      if r.status_code != 200:
                          raise SystemExit(f"login failed: {r.status_code} {r.text}")
                      return r.json()["access_token"]

                  def ensure_user(token, localpart, password, admin):
                      headers = {"Authorization": f"Bearer {token}"}
                      user_id = f"@{localpart}:live.bstein.dev"
                      url = f"{BASE}/_synapse/admin/v2/users/{urllib.parse.quote(user_id)}"
                      res = requests.get(url, headers=headers)
                      if res.status_code == 200:
                          return
                      payload = {"password": password, "admin": admin, "deactivated": False}
                      create = requests.put(url, headers=headers, json=payload)
                      if create.status_code not in (200, 201):
                          raise SystemExit(f"create user {user_id} failed: {create.status_code} {create.text}")

                  def ensure_room(token):
                      headers = {"Authorization": f"Bearer {token}"}
                      alias = "#othrys:live.bstein.dev"
                      alias_enc = "%23othrys%3Alive.bstein.dev"
                      exists = requests.get(f"{BASE}/_matrix/client/v3/directory/room/{alias_enc}", headers=headers)
                      if exists.status_code == 200:
                          room_id = exists.json()["room_id"]
                      else:
                          create = requests.post(f"{BASE}/_matrix/client/v3/createRoom", headers=headers, json={
                              "preset": "public_chat",
                              "name": "Othrys",
                              "room_alias_name": "othrys",
                              "initial_state": [],
                              "power_level_content_override": {"events_default": 0, "users_default": 0, "state_default": 50},
                          })
                          if create.status_code not in (200, 409):
                              raise SystemExit(f"create room failed: {create.status_code} {create.text}")
                          exists = requests.get(f"{BASE}/_matrix/client/v3/directory/room/{alias_enc}", headers=headers)
                          room_id = exists.json()["room_id"]
                      state_events = [
                          ("m.room.join_rules", {"join_rule": "public"}),
                          ("m.room.guest_access", {"guest_access": "can_join"}),
                          ("m.room.history_visibility", {"history_visibility": "shared"}),
                          ("m.room.canonical_alias", {"alias": alias}),
                      ]
                      for ev_type, content in state_events:
                          requests.put(f"{BASE}/_matrix/client/v3/rooms/{room_id}/state/{ev_type}", headers=headers, json=content)
                      requests.put(f"{BASE}/_matrix/client/v3/directory/list/room/{room_id}", headers=headers, json={"visibility": "public"})
                      return room_id

                  def join_user(token, room_id, user_id):
                      headers = {"Authorization": f"Bearer {token}"}
                      requests.post(f"{BASE}/_synapse/admin/v1/join/{urllib.parse.quote(room_id)}", headers=headers, json={"user_id": user_id})

                  def join_all_locals(token, room_id):
                      headers = {"Authorization": f"Bearer {token}"}
                      users = []
                      from_token = None
                      while True:
                          url = f"{BASE}/_synapse/admin/v2/users?local=true&deactivated=false&limit=100"
                          if from_token:
                              url += f"&from={from_token}"
                          res = requests.get(url, headers=headers).json()
                          users.extend([u["name"] for u in res.get("users", [])])
                          from_token = res.get("next_token")
                          if not from_token:
                              break
                      for uid in users:
                          join_user(token, room_id, uid)

                  token = login(os.environ["SEEDER_USER"], os.environ["SEEDER_PASS"])
                  ensure_user(token, os.environ["SEEDER_USER"], os.environ["SEEDER_PASS"], admin=True)
                  ensure_user(token, os.environ["BOT_USER"], os.environ["BOT_PASS"], admin=False)
                  room_id = ensure_room(token)
                  join_user(token, room_id, f"@{os.environ['BOT_USER']}:live.bstein.dev")
                  join_all_locals(token, room_id)
                  PY
              volumeMounts:
                - name: synapse-config
                  mountPath: /config
                  readOnly: true
                - name: vault-scripts
                  mountPath: /vault/scripts
                  readOnly: true
          volumes:
            - name: synapse-config
              secret:
                secretName: othrys-synapse-matrix-synapse
            - name: vault-scripts
              configMap:
                name: comms-vault-env
                defaultMode: 0555
