---
# Playbook to configure OpenShift Cluster using roles
- name: Configure OpenShift cluster
  hosts: localhost
  connection: local
  gather_facts: false
  vars_files:
    - ../secrets.yml

  pre_tasks:
    - name: Ensure required collections are available
      ansible.builtin.debug:
        msg: "Ensuring kubernetes.core collection is available in execution environment"
    
    - 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: Check if this is a hub cluster
      ansible.builtin.set_fact:
        is_hub_cluster: "{{ vars[cluster_region][cluster_name]['is_hub'] | default(false) }}"
        openshift_default_storage_class: "{{ vars[cluster_region][cluster_name]['storage_class'] | default('gitea-local-storage') }}"

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

  roles:
    # Authentication setup
    - role: kubernetes_auth
      tags: 
        - always
        - auth
    
    # Namespace and secrets setup
    - role: namespace_setup
      tags:
        - namespaces
        - secrets
    
    # OAuth and identity provider configuration
    - role: oauth_configuration
      tags:
        - oauth
        - identity
    
    # RBAC setup
    - role: rbac_setup
      tags:
        - rbac
        - permissions
    
    # Optional hub cluster roles
    - role: gitea_deployment
      vars:
        gitea_storage_class_name: "{{ openshift_default_storage_class }}"
        gitea_admin_username: "{{ global.gitea.admin_username | default('gitea_admin') }}"
        gitea_admin_password: "{{ global.gitea.admin_password | default('gitea_admin') }}"
        gitea_admin_email: "{{ global.gitea.admin_email | default('gitea@container.mom') }}"
        gitea_db_password: "{{ global.gitea.db_password | default('gitea') }}"
        gitea_root_url: "https://git.container.mom"
        gitea_domain: "git.container.mom"
        gitea_ssh_domain: "git.container.mom"
      when: is_hub_cluster | bool
      tags: 
        - gitea
        - git
    
    # ArgoCD deployment
    - role: argocd_deployment
      tags:
        - argocd
        - gitops
  
  post_tasks:
    - name: Cleanup temporary files
      ansible.builtin.file:
        path: "{{ kubeconfig_cleanup_dir }}"
        state: absent
      when: kubeconfig_cleanup_required | default(false)
      ignore_errors: true 