apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "grafana.fullname" . }}-org-setup
  namespace: {{ .Values.namespace | default .Release.Namespace }}
  labels:
    {{- include "grafana.labels" . | nindent 4 }}
  annotations:
    "helm.sh/hook": post-install,post-upgrade
    "helm.sh/hook-weight": "1"
    "helm.sh/hook-delete-policy": before-hook-creation
spec:
  template:
    metadata:
      labels:
        {{- include "grafana.selectorLabels" . | nindent 8 }}
        app.kubernetes.io/component: org-setup
    spec:
      restartPolicy: OnFailure
      serviceAccountName: {{ include "grafana.fullname" . }}
      containers:
      - name: org-setup
        image: curlimages/curl:8.4.0
        command:
        - /bin/sh
        - -c
        - |
          set -e
          echo "Setting up Container Mom customer organizations in Grafana..."
          
          # Wait for Grafana to be ready
          GRAFANA_URL="http://{{ include "grafana.fullname" . }}.{{ .Values.namespace | default .Release.Namespace }}.svc.cluster.local"
          echo "Waiting for Grafana at $GRAFANA_URL to be ready..."
          
          until curl -s -o /dev/null -w "%{http_code}" "$GRAFANA_URL/api/health" | grep -q "200"; do
            echo "Waiting for Grafana to start..."
            sleep 5
          done
          
          echo "Grafana is ready. Setting up organizations..."
          
          # Get list of customer namespaces from Kubernetes API
          KUBE_TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
          KUBE_API="https://kubernetes.default.svc"
          
          # Get all customer namespaces
          NAMESPACES=$(curl -s -k -H "Authorization: Bearer $KUBE_TOKEN" \
            "$KUBE_API/api/v1/namespaces?labelSelector=container.mom/customer=true" | \
            grep '"name"' | cut -d'"' -f4 | grep "^customer-")
          
          # Create organization for each customer
          for ns in $NAMESPACES; do
            CUSTOMER_ID=$(echo $ns | sed 's/customer-//')
            ORG_NAME="Customer $CUSTOMER_ID"
            
            echo "Creating organization for $ORG_NAME..."
            
            # Check if org already exists
            ORG_EXISTS=$(curl -s -u admin:${GRAFANA_ADMIN_PASSWORD} \
              "$GRAFANA_URL/api/orgs/name/$ORG_NAME" | grep -c '"id"' || true)
            
            if [ "$ORG_EXISTS" -eq 0 ]; then
              # Create organization
              curl -s -X POST -u admin:${GRAFANA_ADMIN_PASSWORD} \
                -H "Content-Type: application/json" \
                -d "{\"name\":\"$ORG_NAME\"}" \
                "$GRAFANA_URL/api/orgs"
              
              # Get org ID
              ORG_ID=$(curl -s -u admin:${GRAFANA_ADMIN_PASSWORD} \
                "$GRAFANA_URL/api/orgs/name/$ORG_NAME" | grep '"id"' | cut -d':' -f2 | cut -d',' -f1)
              
              # Add data source for this org
              curl -s -X POST -u admin:${GRAFANA_ADMIN_PASSWORD} \
                -H "Content-Type: application/json" \
                -H "X-Grafana-Org-Id: $ORG_ID" \
                -d '{
                  "name": "Prometheus",
                  "type": "prometheus",
                  "url": "http://prometheus-server.monitoring.svc.cluster.local",
                  "access": "proxy",
                  "isDefault": true,
                  "jsonData": {
                    "timeInterval": "30s",
                    "customQueryParameters": "namespace='$ns'"
                  }
                }' \
                "$GRAFANA_URL/api/datasources"
              
              echo "Created organization for $ORG_NAME with ID $ORG_ID"
            else
              echo "Organization $ORG_NAME already exists, skipping..."
            fi
          done
          
          echo "Multi-tenant organization setup complete!"
        env:
        - name: GRAFANA_ADMIN_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ include "grafana.fullname" . }}-admin
              key: admin-password
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "grafana.fullname" . }}
  namespace: {{ .Values.namespace | default .Release.Namespace }}
  labels:
    {{- include "grafana.labels" . | nindent 4 }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ include "grafana.fullname" . }}-namespace-reader
  labels:
    {{- include "grafana.labels" . | nindent 4 }}
rules:
- apiGroups: [""]
  resources: ["namespaces"]
  verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {{ include "grafana.fullname" . }}-namespace-reader
  labels:
    {{- include "grafana.labels" . | nindent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ include "grafana.fullname" . }}-namespace-reader
subjects:
- kind: ServiceAccount
  name: {{ include "grafana.fullname" . }}
  namespace: {{ .Values.namespace | default .Release.Namespace }}