---
# Managed Cluster Integration Tasks

# Ensure the container-mom-system namespace exists
- name: Ensure container-mom-system namespace exists
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: v1
      kind: Namespace
      metadata:
        name: "{{ container_mom_system_namespace }}"
    kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
    validate_certs: "{{ k8s_auth_params.validate_certs }}"

# Initialize empty managed_clusters list
- name: Initialize empty managed_clusters list
  ansible.builtin.set_fact:
    managed_clusters: []

# Show discovered regions for better debugging
- name: Display discovered regions
  ansible.builtin.debug:
    msg: "Processing regions: {{ managed_regions }}"

# Loop through each region
- name: Loop through each region
  include_tasks: process_region.yml
  loop: "{{ managed_regions | default([]) }}"
  loop_control:
    loop_var: current_region
  when: managed_regions is defined

# Create comprehensive cluster access secrets for all managed clusters
- name: Create comprehensive cluster access secrets for all managed clusters
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: v1
      kind: Secret
      metadata:
        name: "{{ item.cluster }}-{{ item.region }}-cluster-access"
        namespace: "{{ container_mom_system_namespace }}"
        labels:
          container-mom.io/cluster-type: "managed"
          container-mom.io/region: "{{ item.region }}"
      type: Opaque
      stringData:
        # Access kubeadmin password from vault using the region and cluster as keys
        password: "{{ vars[item.region][item.cluster].kubeadmin_password }}"
        username: "kubeadmin"
        cluster_name: "{{ item.cluster }}"
        region: "{{ item.region }}"
        api_url: "https://api.{{ item.cluster }}.{{ item.region }}.container.mom:6443"
    kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
    validate_certs: "{{ k8s_auth_params.validate_certs }}"
  loop: "{{ managed_clusters | default([]) }}"

# Workload ArgoCD Integration
- name: Set up Workload ArgoCD integration
  when: workload_argocd_enabled | bool
  block:
    - name: Create wkl-argocd namespace if it doesn't exist
      kubernetes.core.k8s:
        state: present
        definition:
          apiVersion: v1
          kind: Namespace
          metadata:
            name: "{{ workload_argocd_namespace }}"
            labels:
              app.kubernetes.io/name: "{{ workload_argocd_namespace }}"
              app.kubernetes.io/part-of: container-mom
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"

    # Get list of managed cluster secrets
    - name: Get list of managed cluster secrets
      kubernetes.core.k8s_info:
        api_version: v1
        kind: Secret
        namespace: "{{ container_mom_system_namespace }}"
        label_selectors:
          - container-mom.io/cluster-type=managed
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      register: managed_cluster_secrets
      ignore_errors: true

    # Create ArgoCD cluster secrets for each managed cluster
    - name: Create ArgoCD cluster secrets for each managed cluster
      kubernetes.core.k8s:
        state: present
        definition:
          apiVersion: v1
          kind: Secret
          metadata:
            name: "managed-cluster-{{ item.metadata.name }}"
            namespace: "{{ workload_argocd_namespace }}"
            labels:
              argocd.argoproj.io/secret-type: cluster
          type: Opaque
          stringData:
            name: "{{ item.data.cluster_name | b64decode }}-{{ item.data.region | b64decode }}"
            server: "{{ item.data.api_url | b64decode }}"
            config: |
              {
                "tlsClientConfig": {
                  "insecure": false
                }
              }
            username: "{{ item.data.username | b64decode }}"
            password: "{{ item.data.password | b64decode }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      loop: "{{ managed_cluster_secrets.resources | default([]) }}"
      when: managed_cluster_secrets.resources is defined

    # Grant workload ArgoCD cluster-admin access to managed clusters
    - name: Create cluster-admin ClusterRoleBinding for workload ArgoCD
      kubernetes.core.k8s:
        state: present
        definition:
          apiVersion: rbac.authorization.k8s.io/v1
          kind: ClusterRoleBinding
          metadata:
            name: wkl-argocd-cluster-admin
          roleRef:
            apiGroup: rbac.authorization.k8s.io
            kind: ClusterRole
            name: cluster-admin
          subjects:
          - kind: ServiceAccount
            name: "{{ workload_argocd_namespace }}-application-controller"
            namespace: "{{ workload_argocd_namespace }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"

    # Create GitHub repository credentials secret for workload ArgoCD
    - name: Create GitHub repo credentials secret for workload ArgoCD
      kubernetes.core.k8s:
        state: present
        definition:
          apiVersion: v1
          kind: Secret
          metadata:
            name: wkl-argocd-github-repo
            namespace: "{{ workload_argocd_namespace }}"
            labels:
              argocd.argoproj.io/secret-type: repository
          type: Opaque
          stringData:
            type: git
            url: "https://github.com/pfeifferj/container-mom-go.git"
            username: "pfeifferj"
            password: "{{ global.repo_token | default('') }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"

    # Create Gitea/Forgejo repository credentials secret for workload ArgoCD
    - name: Create Forgejo repo credentials secret for workload ArgoCD
      kubernetes.core.k8s:
        state: present
        definition:
          apiVersion: v1
          kind: Secret
          metadata:
            name: wkl-argocd-forgejo-repo
            namespace: "{{ workload_argocd_namespace }}"
            labels:
              argocd.argoproj.io/secret-type: repository
          type: Opaque
          stringData:
            type: git
            url: "https://git.container.mom"
            username: "{{ global.forgejo.admin_username | default('forgejo_admin') }}"
            password: "{{ global.forgejo.admin_password | default('forgejo_admin') }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
