#!/bin/bash
set -euo pipefail

# ================================================================
# Setup PG credentials for an ESS Matrix instance
# ================================================================
# Generates random passwords, updates CNPG roles, applies a
# Kubernetes Secret in the instance namespace, and updates the
# matching pg-secret.yaml file in the repo.
#
# Usage: ./setup-pg-creds.sh <homeserver-name>
# Example: ./setup-pg-creds.sh mrt0rtikize
# ================================================================

readonly YC_KUBECONFIG="${KUBECONFIG:-/home/mrt0rtikize/infra/yandex-prod/kubeconfig}"
readonly K="${KUBECTL:-kubectl} --kubeconfig ${YC_KUBECONFIG}"
readonly REPO_DIR="$(dirname "$(realpath "$0")")/.."

readonly CNPG_NS="cnpg"
readonly CNPG_POD="shared-pg-1"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
log()  { echo -e "${GREEN}[$(date +%H:%M:%S)]${NC} $*"; }
err()  { echo -e "${RED}[$(date +%H:%M:%S)] ERROR:${NC} $*"; }

# -------------------------------------------------------------------
# Parse argument
# -------------------------------------------------------------------
NAME="${1:?Usage: $0 <homeserver-name>}"
NS="matrix-${NAME}"
DB_SYNAPSE="synapse_${NAME}"
DB_MAS="mas_${NAME}"
USER_SYNAPSE="synapse_${NAME}"
USER_MAS="mas_${NAME}"

# -------------------------------------------------------------------
# Prerequisites
# -------------------------------------------------------------------
log "=== Setting up PG credentials for ${NAME} ==="

if ! ${K} get ns "${NS}" >/dev/null 2>&1; then
    err "Namespace ${NS} not found. Deploy the ESS app first."
    exit 1
fi

if ! ${K} -n "${CNPG_NS}" get pod "${CNPG_POD}" >/dev/null 2>&1; then
    err "CNPG pod ${CNPG_POD} not found."
    exit 1
fi

# -------------------------------------------------------------------
# Generate passwords
# -------------------------------------------------------------------
log "Generating passwords..."

SYNAPSE_PW=$(openssl rand -base64 24 | tr -d '\n')
MAS_PW=$(openssl rand -base64 24 | tr -d '\n')

# -------------------------------------------------------------------
# Update PostgreSQL roles
# -------------------------------------------------------------------
log "Creating/updating CNPG role: ${USER_SYNAPSE}"
${K} exec -n "${CNPG_NS}" "${CNPG_POD}" -- \
    psql -U postgres -c "DO \$\$ BEGIN IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '${USER_SYNAPSE}') THEN CREATE ROLE ${USER_SYNAPSE} WITH LOGIN PASSWORD '${SYNAPSE_PW}'; ELSE ALTER ROLE ${USER_SYNAPSE} WITH PASSWORD '${SYNAPSE_PW}'; END IF; END \$\$;"

log "Creating/updating CNPG role: ${USER_MAS}"
${K} exec -n "${CNPG_NS}" "${CNPG_POD}" -- \
    psql -U postgres -c "DO \$\$ BEGIN IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '${USER_MAS}') THEN CREATE ROLE ${USER_MAS} WITH LOGIN PASSWORD '${MAS_PW}'; ELSE ALTER ROLE ${USER_MAS} WITH PASSWORD '${MAS_PW}'; END IF; END \$\$;"

# -------------------------------------------------------------------
# Apply Kubernetes Secret
# -------------------------------------------------------------------
log "Creating/updating Kubernetes Secret pg-creds in ${NS}..."

${K} create secret generic pg-creds -n "${NS}" \
    --from-literal=synapse="${SYNAPSE_PW}" \
    --from-literal=mas="${MAS_PW}" \
    --dry-run=client -o yaml | ${K} apply -f -

# -------------------------------------------------------------------
# Update repo file
# -------------------------------------------------------------------
SECRET_FILE="${REPO_DIR}/manifests/${NS}/pg-secret.yaml"
if [ -f "${SECRET_FILE}" ]; then
    log "Updating ${SECRET_FILE}..."

    cat > "${SECRET_FILE}" <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: pg-creds
  namespace: ${NS}
  labels:
    app.kubernetes.io/part-of: matrix-stack
type: Opaque
stringData:
  synapse: ${SYNAPSE_PW}
  mas: ${MAS_PW}
EOF
    log "Repo file updated."
else
    log "File ${SECRET_FILE} does not exist — skipping repo update."
    log "The Secret is live in the cluster (not in git). Create the file manually."
fi

# -------------------------------------------------------------------
# Restart pods
# -------------------------------------------------------------------
log "Restarting pods to pick up new credentials..."

${K} delete pod -n "${NS}" -l "app.kubernetes.io/component=matrix-server" --ignore-not-found 2>/dev/null
${K} delete pod -n "${NS}" -l "app.kubernetes.io/component=matrix-authentication" --ignore-not-found 2>/dev/null

# -------------------------------------------------------------------
# Summary
# -------------------------------------------------------------------
echo ""
echo "Synapse password: ${SYNAPSE_PW}"
echo "MAS password:     ${MAS_PW}"
echo ""
echo "Done. Synapse + MAS pods are restarting with new credentials."
