- name: "Add Keycloak OIDC Provider"
  shell: |
    docker exec -i --user {{ gitea_user }} {{ gitea_container }} \
      gitea admin auth add-oauth \
        --provider openidConnect \
        --name     "{{ OIDC.BUTTON_TEXT }}" \
        --key      "{{ OIDC.CLIENT.ID }}" \
        --secret   "{{ OIDC.CLIENT.SECRET }}" \
        --auto-discover-url "{{ OIDC.CLIENT.DISCOVERY_DOCUMENT }}" \
        --scopes   "openid profile email"
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: oidc_manage
  failed_when: oidc_manage.rc != 0 and "login source already exists" not in oidc_manage.stderr

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

- name: "Set Keycloak source ID fact"
  set_fact:
    oidc_source_id: "{{ oidc_source_id_raw.stdout }}"

- name: "Update Keycloak OIDC Provider"
  shell: |
    docker exec -i --user {{ gitea_user }} {{ gitea_container }} \
      gitea admin auth update-oauth \
        --id {{ oidc_source_id }}\
        --provider openidConnect \
        --name     "{{ OIDC.BUTTON_TEXT }}" \
        --key      "{{ OIDC.CLIENT.ID }}" \
        --secret   "{{ OIDC.CLIENT.SECRET }}" \
        --auto-discover-url "{{ OIDC.CLIENT.DISCOVERY_DOCUMENT }}" \
        --scopes   "openid profile email"
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: oidc_manage
  failed_when: oidc_manage.rc != 0