---
# Initialize local storage directories for Forgejo

- name: Create ServiceAccount for storage initialization
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: v1
      kind: ServiceAccount
      metadata:
        name: forgejo-storage-init
        namespace: "{{ forgejo_namespace }}"
    kubeconfig: "{{ k8s_auth_params.kubeconfig | default(omit) }}"
    validate_certs: "{{ k8s_auth_params.validate_certs | default(true) }}"

- name: Add privileged SCC to storage init ServiceAccount
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: rbac.authorization.k8s.io/v1
      kind: ClusterRoleBinding
      metadata:
        name: forgejo-storage-init-privileged
      roleRef:
        apiGroup: rbac.authorization.k8s.io
        kind: ClusterRole
        name: system:openshift:scc:privileged
      subjects:
      - kind: ServiceAccount
        name: forgejo-storage-init
        namespace: "{{ forgejo_namespace }}"
    kubeconfig: "{{ k8s_auth_params.kubeconfig | default(omit) }}"
    validate_certs: "{{ k8s_auth_params.validate_certs | default(true) }}"

- name: Delete existing storage init job if it exists
  kubernetes.core.k8s:
    state: absent
    api_version: batch/v1
    kind: Job
    namespace: "{{ forgejo_namespace }}"
    name: forgejo-storage-init
    kubeconfig: "{{ k8s_auth_params.kubeconfig | default(omit) }}"
    validate_certs: "{{ k8s_auth_params.validate_certs | default(true) }}"
  ignore_errors: true

- name: Initialize local storage directories with Job
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: batch/v1
      kind: Job
      metadata:
        name: forgejo-storage-init
        namespace: "{{ forgejo_namespace }}"
      spec:
        ttlSecondsAfterFinished: 600
        template:
          spec:
            serviceAccountName: forgejo-storage-init
            restartPolicy: Never
            containers:
              - name: init-local-dirs
                image: registry.redhat.io/openshift4/ose-cli:latest
                command: ["/bin/bash", "-c"]
                args:
                  - |
                    # Make sure the base directory exists and is accessible
                    echo "Checking base directories..."
                    mkdir -p /var/tmp
                    chmod 777 /var/tmp

                    # Forgejo main data dir
                    echo "Creating Forgejo directories..."
                    mkdir -p {{ forgejo_data_path }}
                    chmod 777 {{ forgejo_data_path }}

                    # PostgreSQL HA data dirs
                    echo "Creating PostgreSQL HA directories..."
                    mkdir -p {{ postgresql_ha_data_path }}-0
                    mkdir -p {{ postgresql_ha_data_path }}-1
                    mkdir -p {{ postgresql_ha_data_path }}-2
                    chmod 777 {{ postgresql_ha_data_path }}-0
                    chmod 777 {{ postgresql_ha_data_path }}-1
                    chmod 777 {{ postgresql_ha_data_path }}-2

                    # Redis data dirs for cluster
                    echo "Creating Redis directories..."
                    mkdir -p {{ redis_data_path }}-cluster-0
                    mkdir -p {{ redis_data_path }}-cluster-1
                    mkdir -p {{ redis_data_path }}-cluster-2
                    mkdir -p {{ redis_data_path }}-master
                    chmod 777 {{ redis_data_path }}-cluster-0
                    chmod 777 {{ redis_data_path }}-cluster-1
                    chmod 777 {{ redis_data_path }}-cluster-2
                    chmod 777 {{ redis_data_path }}-master

                    # Set ownership to allow containers with random UIDs
                    echo "Setting ownership..."
                    chown -R 1000880000:1000880000 {{ forgejo_data_path }}
                    chown -R 1000880000:1000880000 {{ postgresql_ha_data_path }}-0
                    chown -R 1000880000:1000880000 {{ postgresql_ha_data_path }}-1
                    chown -R 1000880000:1000880000 {{ postgresql_ha_data_path }}-2
                    chown -R 1000880000:1000880000 {{ redis_data_path }}-cluster-0
                    chown -R 1000880000:1000880000 {{ redis_data_path }}-cluster-1
                    chown -R 1000880000:1000880000 {{ redis_data_path }}-cluster-2
                    chown -R 1000880000:1000880000 {{ redis_data_path }}-master

                    # List the directories for verification
                    echo "Created directories:"
                    ls -la {{ forgejo_data_path }} | head -n 5
                    ls -la {{ postgresql_ha_data_path }}-0 | head -n 5
                    ls -la {{ postgresql_ha_data_path }}-1 | head -n 5
                    ls -la {{ postgresql_ha_data_path }}-2 | head -n 5
                    ls -la {{ redis_data_path }}-cluster-0 | head -n 5
                    ls -la {{ redis_data_path }}-cluster-1 | head -n 5
                    ls -la {{ redis_data_path }}-cluster-2 | head -n 5
                    ls -la {{ redis_data_path }}-master | head -n 5

                    echo "All storage directories created successfully!"
                securityContext:
                  privileged: true
                volumeMounts:
                  - name: host-path
                    mountPath: /var
            volumes:
              - name: host-path
                hostPath:
                  path: /var
                  type: Directory
            nodeSelector:
              kubernetes.io/hostname: "{{ forgejo_node_hostname }}"
    kubeconfig: "{{ k8s_auth_params.kubeconfig | default(omit) }}"
    validate_certs: "{{ k8s_auth_params.validate_certs | default(true) }}"

- name: Wait for storage initialization to complete
  kubernetes.core.k8s_info:
    api_version: batch/v1
    kind: Job
    name: forgejo-storage-init
    namespace: "{{ forgejo_namespace }}"
    kubeconfig: "{{ k8s_auth_params.kubeconfig | default(omit) }}"
    validate_certs: "{{ k8s_auth_params.validate_certs | default(true) }}"
  register: job_result
  until: job_result.resources[0].status.succeeded is defined and job_result.resources[0].status.succeeded == 1
  retries: "{{ forgejo_storage_init_retries }}"
  delay: "{{ forgejo_storage_init_delay }}"
