#!/bin/bash -eu

source /etc/env

SERVER_NAME=$(gum input --placeholder "Server name - example.org")
OIDC_CLIENT_SECRET=$(gum input --placeholder "Oidc client secret - synapse to create in keycloak")
NS=${SERVER_NAME/./-}

kubectl create ns ${NS}

SMTP_SECRET=$(gum input --placeholder "Smtp secret - on pm1 - kubectl -n ${NS} get secrets ${NS}-smtp -o json | jq -r ".data.password" | base64 -d")
S3_SECRET_KEY=$(gum input --placeholder "S3 Secret Key for dumps - on pm1 - kubectl -n ${NS} get secrets ${NS}-dumps -o json | jq -r ".data.AWS_SECRET_ACCESS_KEY" | base64 -d")

MACAROON_SECRET=$(base64 /dev/urandom | head -c 32)
REDIS_SECRET=$(base64 /dev/urandom | head -c 32)

cat << EOF > matrix-secret.yml
---
apiVersion: v1
kind: Secret
metadata:
  name: matrix-config
  namespace: $NS
type: Opaque
stringData:
  SERVER_NAME: "$SERVER_NAME"
  ELEMENT_SUBDOMAIN: "chat"
  S3_BUCKET: "$NS-dumps"
  S3_SECRET_KEY: "$S3_SECRET_KEY"
  TURN_SECRET: "$TURN_SECRET"
  MACAROON_SECRET: "$MACAROON_SECRET"
  SMTP_USER_FROM: "$NS@liiib.re"
  SMTP_SECRET: "$SMTP_SECRET"
  OIDC_ISSUER: "https://id.$SERVER_NAME/auth/realms/$NS"
  CLIENT_SECRET: "$OIDC_CLIENT_SECRET"
  REDIS_SECRET: "$REDIS_SECRET"
  USER_DIRECTORY_SEARCH_ALL: "false"
  HOME_URL: "https://nuage.$SERVER_NAME"
---
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
  name: matrix
  namespace: $NS
spec:
  interval: 10m
  path: "."
  prune: true
  targetNamespace: ""
  sourceRef:
    kind: GitRepository
    name: matrix-kustomize
    namespace: flux-system
  postBuild:
    substituteFrom:
      - kind: Secret
        name: matrix-config
EOF

cat << EOF > matrix-ingress.yml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt
    kubernetes.io/tls-acme: "true"
  name: matrix
  namespace: $NS
spec:
  rules:
    - host: $SERVER_NAME
      http:
        paths:
          - backend:
              service:
                name: synapse-wellknown-lighttpd
                port:
                  number: 80
            path: /.well-known/matrix
            pathType: Prefix
  tls:
    - hosts:
        - $SERVER_NAME
      secretName: $NS-tls
EOF