---
# Install Forgejo using Helm

- name: Verify Forgejo vault credentials are available
  ansible.builtin.assert:
    that:
      - global is defined
      - global.forgejo is defined
      - global.forgejo.admin_username is defined
      - global.forgejo.admin_password is defined
      - global.forgejo.admin_email is defined
      - global.forgejo.db_password is defined
    fail_msg: "Required Forgejo credentials not found in vault. Please ensure global.forgejo.* variables are set."
    quiet: yes

- name: Get Forgejo admin credentials from vault
  ansible.builtin.set_fact:
    forgejo_admin_username: "{{ global.forgejo.admin_username }}"
    forgejo_admin_password: "{{ global.forgejo.admin_password }}"
    forgejo_admin_email: "{{ global.forgejo.admin_email }}"
    forgejo_db_password: "{{ global.forgejo.db_password }}"

- name: Create values file from template
  ansible.builtin.template:
    src: forgejo_values.yaml.j2
    dest: "/tmp/forgejo_values_{{ forgejo_namespace }}.yaml"
  register: values_template

# Build PVC list based on PostgreSQL configuration
- name: Set PVC list for PostgreSQL standard
  ansible.builtin.set_fact:
    pvc_check_list:
      - "gitea-shared-storage"
      - "data-forgejo-postgresql"
      - "redis-data-forgejo-redis-master"
  when: not forgejo_use_postgres_ha | default(false)

- name: Install Forgejo using Helm
  kubernetes.core.helm:
    name: "{{ forgejo_helm_release_name }}"
    chart_ref: "{{ forgejo_helm_chart_ref }}"
    chart_version: "{{ forgejo_helm_chart_version }}"
    release_namespace: "{{ forgejo_namespace }}"
    create_namespace: false
    wait: true
    wait_timeout: "{{ forgejo_helm_wait_timeout }}"
    force: true
    values: "{{ lookup('template', 'forgejo_values.yaml.j2') | from_yaml }}"
    kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
    validate_certs: "{{ k8s_auth_params.validate_certs }}"
  register: helm_result

- name: Clean up temporary values file
  ansible.builtin.file:
    path: "{{ values_template.dest }}"
    state: absent
  when: values_template.dest is defined

- name: Show Helm installation result
  ansible.builtin.debug:
    var: helm_result
    verbosity: 1
