---
# Playbook to clean up ArgoCD, Cert Manager, and container-mom-system namespaces
- name: Clean up OpenShift resources for testing
  hosts: localhost
  connection: local
  gather_facts: false
  vars_files:
    - ../secrets.yml

  pre_tasks:
    - name: Verify cluster variables are set
      ansible.builtin.assert:
        that:
          - cluster_region is defined
          - cluster_name is defined
        fail_msg: "Cluster region and name must be defined in inventory"

    - name: Retrieve kubeadmin password for the cluster
      ansible.builtin.set_fact:
        kubeadmin_password: "{{ vars[cluster_region][cluster_name]['kubeadmin_password'] | default('') }}"

    - name: Verify kubeadmin password exists
      ansible.builtin.assert:
        that: kubeadmin_password | length > 0
        fail_msg: "Kubeadmin password for {{ cluster_region }}.{{ cluster_name }} not found in vault"

  roles:
    - role: kubernetes_auth

  tasks:
    - name: Warn user about cleanup
      ansible.builtin.pause:
        prompt: "This playbook will delete ArgoCD, Cert-Manager, container-mom-system, container-mom-portal, container-mom-landing, and associated test namespaces. Press Enter to continue or Ctrl+C to cancel"

    # First, find and remove finalizers from all ArgoCD Application resources
    - name: Get all ArgoCD Application resources in the cluster
      kubernetes.core.k8s_info:
        api_version: argoproj.io/v1alpha1
        kind: Application
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      register: argocd_applications
      ignore_errors: true

    - name: Remove finalizers from ArgoCD Application resources
      kubernetes.core.k8s:
        state: patched
        api_version: argoproj.io/v1alpha1
        kind: Application
        name: "{{ item.metadata.name }}"
        namespace: "{{ item.metadata.namespace }}"
        definition:
          metadata:
            finalizers: null
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      loop: "{{ argocd_applications.resources | default([]) }}"
      ignore_errors: true

    # Then delete ALL ArgoCD Application resources in the cluster
    - name: Remove ALL ArgoCD Application resources
      kubernetes.core.k8s:
        state: absent
        api_version: argoproj.io/v1alpha1
        kind: Application
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    # The existing resource cleanup can remain, as a fallback
    - name: Remove ArgoCD Application resources (specific)
      kubernetes.core.k8s:
        state: absent
        api_version: argoproj.io/v1alpha1
        kind: Application
        name: app-of-apps
        namespace: argocd
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    # Remove ArgoCD resources first
    - name: Remove ArgoCD Project resources
      kubernetes.core.k8s:
        state: absent
        api_version: argoproj.io/v1alpha1
        kind: AppProject
        name: container-mom
        namespace: argocd
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    - name: Remove CertManager ClusterIssuer
      kubernetes.core.k8s:
        state: absent
        api_version: cert-manager.io/v1
        kind: ClusterIssuer
        name: letsencrypt-prod
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    # Use Helm to uninstall ArgoCD
    - name: Uninstall ArgoCD using Helm
      kubernetes.core.helm:
        name: argocd
        release_namespace: argocd
        state: absent
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    # Use Helm to uninstall Cert Manager
    - name: Uninstall Cert Manager using Helm
      kubernetes.core.helm:
        name: cert-manager
        release_namespace: cert-manager
        state: absent
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    # Wait a bit for finalizers to complete
    - name: Wait for finalizers to complete
      ansible.builtin.pause:
        seconds: 15

    - name: Remove ArgoCD namespace (if still exists)
      kubernetes.core.k8s:
        state: absent
        api_version: v1
        kind: Namespace
        name: argocd
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    - name: Remove Cert Manager namespace (if still exists)
      kubernetes.core.k8s:
        state: absent
        api_version: v1
        kind: Namespace
        name: cert-manager
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    # Get all workload namespaces (dynamic discovery)
    - name: Find all workload namespaces (starting with wkl-)
      kubernetes.core.k8s_info:
        api_version: v1
        kind: Namespace
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      register: all_namespaces
      ignore_errors: true

    - name: Filter workload namespaces
      ansible.builtin.set_fact:
        workload_namespaces: "{{ all_namespaces.resources | selectattr('metadata.name', 'match', '^wkl-.*') | map(attribute='metadata.name') | list }}"

    - name: Display workload namespaces to be removed
      ansible.builtin.debug:
        msg: "Found workload namespaces to remove: {{ workload_namespaces }}"
      when: workload_namespaces is defined and workload_namespaces | length > 0

    - name: Remove all wkl- prefixed namespaces
      kubernetes.core.k8s:
        state: absent
        api_version: v1
        kind: Namespace
        name: "{{ item }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop: "{{ workload_namespaces | default([]) }}"

    # Uninstall Helm releases in workload namespaces
    - name: Uninstall workload ArgoCD using Helm
      kubernetes.core.helm:
        name: wkl-argocd
        release_namespace: "{{ item }}"
        state: absent
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop: "{{ workload_namespaces | default([]) | select('match', '^wkl-argocd.*') | list }}"
      when: workload_namespaces is defined and workload_namespaces | length > 0

    - name: Remove container-mom namespaces
      kubernetes.core.k8s:
        state: absent
        api_version: v1
        kind: Namespace
        name: "{{ item }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop:
        - container-mom-system
        - container-mom-system-test
        - container-mom-portal
        - container-mom-portal-test
        - container-mom-landing
        - container-mom-landing-test
        - container-mom-git

    # Clean up all workload ArgoCD specific resources (now handled dynamically above)
    - name: Remove workload ArgoCD ClusterRoleBindings
      kubernetes.core.k8s:
        state: absent
        api_version: rbac.authorization.k8s.io/v1
        kind: ClusterRoleBinding
        name: "{{ item }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop:
        - wkl-argocd-admin
        - wkl-argocd-cluster-admin

    - name: Remove OpenShift OAuth client
      kubernetes.core.k8s:
        state: absent
        api_version: oauth.openshift.io/v1
        kind: OAuthClient
        name: "{{ cluster_name }}-oauth-client"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    - name: Remove Google Secret in openshift-config
      kubernetes.core.k8s:
        state: absent
        api_version: v1
        kind: Secret
        name: google-secret
        namespace: openshift-config
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    - name: Remove ArgoCD ClusterRoleBinding
      kubernetes.core.k8s:
        state: absent
        api_version: rbac.authorization.k8s.io/v1
        kind: ClusterRoleBinding
        name: argocd-cluster-admin
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    - name: Remove Google ClusterRoleBindings
      kubernetes.core.k8s:
        state: absent
        api_version: rbac.authorization.k8s.io/v1
        kind: ClusterRoleBinding
        name: "{{ item }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop:
        - google-cluster-admin
        - google-cluster-viewer-container-mom

    - name: Reset OAuth configuration
      kubernetes.core.k8s:
        state: present
        definition:
          apiVersion: config.openshift.io/v1
          kind: OAuth
          metadata:
            name: cluster
          spec:
            identityProviders: []
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true

    # Clean up Forgejo/Gitea resources
    - name: Remove Gitea/Forgejo ClusterRoleBindings
      kubernetes.core.k8s:
        state: absent
        api_version: rbac.authorization.k8s.io/v1
        kind: ClusterRoleBinding
        name: "{{ item }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop:
        - gitea-privileged
        - gitea-anyuid
        - gitea-storage-init-privileged
        - forgejo-privileged
        - forgejo-anyuid
        - forgejo-storage-init-privileged

    - name: Remove Gitea/Forgejo PersistentVolumes
      kubernetes.core.k8s:
        state: absent
        api_version: v1
        kind: PersistentVolume
        name: "{{ item }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop:
        # Gitea PVs
        - gitea-local-pv-data
        - gitea-local-pv-postgresql
        - gitea-local-pv-postgresql-ha-0
        - gitea-local-pv-postgresql-ha-1
        - gitea-local-pv-postgresql-ha-2
        - gitea-local-pv-redis-0
        - gitea-local-pv-redis-1
        - gitea-local-pv-redis-2
        # Forgejo PVs
        - forgejo-local-pv-data
        - forgejo-local-pv-postgresql
        - pv-gitea-shared-storage
        - pv-postgresql-ha-data-0
        - pv-postgresql-ha-data-1
        - pv-postgresql-ha-data-2
        - pv-redis-cluster-data-0
        - pv-redis-cluster-data-1
        - pv-redis-cluster-data-2
        - pv-redis-master-data

    - name: Remove Gitea/Forgejo StorageClass
      kubernetes.core.k8s:
        state: absent
        api_version: storage.k8s.io/v1
        kind: StorageClass
        name: "{{ item }}"
        kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
        validate_certs: "{{ k8s_auth_params.validate_certs }}"
      ignore_errors: true
      loop:
        - gitea-local-storage
        - forgejo-local-storage

  post_tasks:
    - name: Cleanup temporary files
      ansible.builtin.file:
        path: "{{ kubeconfig_cleanup_dir }}"
        state: absent
      when: kubeconfig_cleanup_required | default(false)
      ignore_errors: true
