---
- name: Install deploy prerequisites
  ansible.builtin.dnf:
    name:
      - gettext
      - jq
      - git
    state: present

- name: Create gitea-runner system user
  ansible.builtin.user:
    name: gitea-runner
    system: true
    shell: /bin/bash
    create_home: true
    home: /var/lib/gitea-runner
    groups: docker
    append: true

- name: Download act_runner binary
  ansible.builtin.get_url:
    url: "https://dl.gitea.com/act_runner/{{ act_runner_version }}/act_runner-{{ act_runner_version }}-{{ act_runner_arch }}"
    dest: /usr/local/bin/act_runner
    mode: "0755"
    owner: root
    group: root
    force: true
  notify: restart act_runner

- name: Create act_runner config directory
  ansible.builtin.file:
    path: /etc/gitea-act-runner
    state: directory
    owner: gitea-runner
    group: gitea-runner
    mode: "0750"

- name: Deploy act_runner config
  ansible.builtin.template:
    src: config.yaml.j2
    dest: /etc/gitea-act-runner/config.yaml
    owner: gitea-runner
    group: gitea-runner
    mode: "0640"
  notify: restart act_runner

# .runner dosyası varsa runner zaten kayıtlıdır; creates ile idempotent hale gelir.
- name: Register runner with Gitea
  ansible.builtin.command:
    argv:
      - /usr/local/bin/act_runner
      - register
      - --instance
      - "{{ act_runner_gitea_url }}"
      - --token
      - "{{ act_runner_registration_token }}"
      - --no-interactive
      - --name
      - "{{ act_runner_name }}"
      - --config
      - /etc/gitea-act-runner/config.yaml
      - --labels
      - "{{ act_runner_labels }}"
  args:
    chdir: /var/lib/gitea-runner
    creates: /var/lib/gitea-runner/.runner
  become_user: gitea-runner
  when: act_runner_registration_token | length > 0
  no_log: true

- name: Deploy gitea-act-runner systemd service
  ansible.builtin.template:
    src: gitea-act-runner.service.j2
    dest: /etc/systemd/system/gitea-act-runner.service
    mode: "0644"
  notify: restart act_runner

- name: Enable and start gitea-act-runner
  ansible.builtin.systemd:
    name: gitea-act-runner
    enabled: true
    state: started
    daemon_reload: true
