- name: "Add LDAP Authentication Source"
  shell: |
    docker exec -i --user {{ gitea_user }} {{ gitea_container }} \
      gitea admin auth add-ldap \
      {{ gitea_ldap_auth_args | join(' ') }}
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: ldap_manage
  failed_when: ldap_manage.rc != 0 and "login source already exists" not in ldap_manage.stderr

- name: "Lookup existing LDAP auth source ID"
  shell: |
    docker exec -i --user {{ gitea_user }} {{ gitea_container }} \
      gitea admin auth list \
      | tail -n +2 \
      | grep -F "LDAP ({{ PRIMARY_DOMAIN }})" \
      | awk '{print $1; exit}'
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: ldap_source_id_raw
  failed_when:
    - ldap_source_id_raw.rc != 0
    - ldap_source_id_raw.stdout == ""
  changed_when: false

- name: "Set LDAP source ID fact"
  set_fact:
    ldap_source_id: "{{ ldap_source_id_raw.stdout }}"

- name: "Update LDAP Authentication Source"
  shell: |
    docker exec -i --user {{ gitea_user }} {{ gitea_container }} \
      gitea admin auth update-ldap \
      --id {{ ldap_source_id }} \
      {{ gitea_ldap_auth_args | join(' ') }}
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: ldap_manage
  failed_when: ldap_manage.rc != 0
