---
- name: Create download directory
  ansible.builtin.file:
    path: '/home/debian/woodpecker-agent-1.0.1'
    state: directory
    mode: '0755'

- name: Download agent tarball
  ansible.builtin.unarchive:
    src: 'https://github.com/woodpecker-ci/woodpecker/releases/download/v1.0.1/woodpecker-agent_linux_arm64.tar.gz'
    remote_src: true
    dest: '/home/debian/woodpecker-agent-1.0.1'
    creates: '/home/debian/woodpecker-agent-1.0.1/woodpecker-agent'
    include:
      - 'woodpecker-agent'
  register: res

- name: Move binary to correct location
  ansible.builtin.copy:
    src: '/home/debian/woodpecker-agent-1.0.1/woodpecker-agent'
    remote_src: true
    dest: '/usr/local/bin/woodpecker-agent'
    owner: 'root'
    group: 'root'
    mode: '0755'
  when: 'res.changed'

- name: Ensure system group exists
  group:
    name: 'woodpecker'
    gid: 200
    system: true
    state: present

- name: Ensure system user exists
  user:
    name: 'woodpecker'
    group: 'woodpecker'
    groups:
      - docker
    uid: 200
    system: true
    create_home: false

- name: Ensure woodpecker directory is present
  file:
    path: '/etc/woodpecker'
    state: directory
    mode: '0755'
    owner: 'woodpecker'
    group: 'woodpecker'

- name: Ensure agent environment file is present
  template:
    src: 'woodpecker-agent.env.j2'
    dest: '/etc/woodpecker/woodpecker-agent.env'
    owner: 'woodpecker'
    group: 'woodpecker'
    mode: '0644'
  notify: woodpecker-agent-restart

- name: Ensure service file is present
  copy:
    src: 'woodpecker-agent.service'
    dest: '/lib/systemd/system/woodpecker-agent.service'
    owner: 'root'
    group: 'root'
    mode: '0644'
  register: res

- name: systemd-reload
  ansible.builtin.systemd_service:
    daemon_reload: true
  when: 'res.changed'

- name: Ensure agent service is enabled
  ansible.builtin.service:
    name: 'woodpecker-agent'
    state: started
    enabled: true
