---
- name: Install building dependencies
  ansible.builtin.apt:
    pkg:
      - npm
      - rsync
    update_cache: true
  become: true

- name: Create groups
  ansible.builtin.group:
    name: "{{ item }}"
  loop:
    - docker
    - forgejo-runner
  become: true

- name: Create forgejo-runner user
  ansible.builtin.user:
    name: forgejo-runner
    groups: docker
    group: forgejo-runner
    password: "!"
    home: "/home/forgejo-runner"
    create_home: true
    system: true
    shell: /bin/bash
    comment: "forgejo-runner system user"
  become: true
  notify: Restart forgejo-runner

- name: Download
  ansible.builtin.get_url:
    url: "{{ byggmester_download_url }}"
    dest: /home/forgejo-runner/forgejo-runner
    mode: "774"
    owner: forgejo-runner
  become: true
  notify: Restart forgejo-runner

- name: Copy runner service
  ansible.builtin.copy:
    src: forgejo-runner.service
    dest: /etc/systemd/system/forgejo-runner.service
    mode: "0644"
    owner: root
  become: true
  notify: Daemon reload

- name: Copy config
  ansible.builtin.copy:
    src: config.yml
    dest: /home/forgejo-runner/config.yml
    mode: "0744"
    owner: forgejo-runner
  become: true
  notify: Restart forgejo-runner

- name: See if runner file already exists
  ansible.builtin.stat:
    path: /home/forgejo-runner/.runner
  register: is_registered
  become: true

- name: Regisert new runner
  when: "not is_registered.stat.exists"
  block:
    - name: Generate secret
      delegate_to: forgejo
      ansible.builtin.command: >-
        /usr/local/bin/forgejo/forgejo forgejo-cli actions generate-secret
      register: generated_secret
      become: true
      become_user: forgejo

    - name: Create a runner on forgejo server
      delegate_to: forgejo
      ansible.builtin.command: >-
        /usr/local/bin/forgejo/forgejo --config /etc/forgejo/app.ini forgejo-cli actions register
          --name    byggmester
          --labels  ubuntu
          --secret  {{ generated_secret.stdout }}
      become: true
      become_user: forgejo

    - name: Join byggmester runner
      ansible.builtin.command: >-
        ./forgejo-runner create-runner-file --instance https://code.polsevev.dev
          --secret {{ generated_secret.stdout }}
      args:
        chdir: "/home/forgejo-runner"
      become: true
      become_user: forgejo-runner
      notify: Restart forgejo-runner

- name: Ensure runnner service is started
  ansible.builtin.service:
    name: forgejo-runner.service
    state: started
    enabled: true
  become: true

- name: Create .ssh
  ansible.builtin.file:
    state: directory
    owner: forgejo-runner
    path: /home/forgejo-runner/.ssh
    group: forgejo-runner
    mode: "0755"
  become: true

- name: Create known hosts
  ansible.builtin.file:
    state: touch
    owner: forgejo-runner
    path: /home/forgejo-runner/.ssh/known_hosts
    group: forgejo-runner
    mode: "0600"
  become: true
