---
- name: "load docker, db and proxy for {{ application_id }}"
  include_role: 
    name: cmp-db-docker-proxy

- name: Wait for Gitea HTTP endpoint
  wait_for:
    host: "127.0.0.1"
    port: "{{ ports.localhost.http[application_id] }}"
    delay: 5
    timeout: 300

- name: Patch Gitea database settings in app.ini
  include_tasks: 01_database.yml

- name: "Run DB migrations inside Gitea container"
  shell: |
    docker exec -i --user {{ gitea_user }} {{ gitea_container }} \
      /app/gitea/gitea migrate
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: migrate
  changed_when: "'migrations completed' in migrate.stdout"

- name: "Create initial admin user"
  shell: |
    docker exec -i --user {{ gitea_user }} {{ gitea_container }} \
      /app/gitea/gitea admin user create \
        --admin \
        --username "{{ users.administrator.username }}" \
        --password "{{ users.administrator.password }}" \
        --email    "{{ users.administrator.email }}" \
        -c {{ gitea_config }}
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: create_admin
  changed_when: "'has been successfully created' in create_admin.stdout"
  failed_when: create_admin.rc != 0 and 'user already exists' not in create_admin.stderr

- name: "Wait until Gitea setup and migrations are ready"
  uri:
    url: "http://127.0.0.1:{{ ports.localhost.http[application_id] }}/api/v1/version"
    method: GET
    status_code: 200
    return_content: no
  register: gitea_ready
  until: gitea_ready.status == 200
  retries: 20
  delay: 5
  when: applications | get_app_conf(application_id, 'features.oidc', False) or applications | get_app_conf(application_id, 'features.ldap', False)

- name: Execute Setup Routines
  include_tasks: 02_setup.yml

- name: Execute Cleanup Routines
  include_tasks: 03_cleanup.yml 
  when: MODE_CLEANUP

- name: Include DNS role to register Gitea domain(s)
  include_role:
    name: sys-dns-cloudflare-records
  vars:
    cloudflare_records:
      - zone:     "{{ domains | get_domain(application_id) | to_zone }}"
        type:     A
        name:    "{{ domains | get_domain(application_id) }}"
        content: "{{ networks.internet.ip4 }}"
        proxied: false  # Necessary for SSH port
  when: DNS_PROVIDER == 'cloudflare'