---

## TODO: add those URLs or domains to the proxy whitelist
# http://pkg.jenkins-ci.org/.*
# http://mirrors.jenkins.io/.*
# http://jenkins.mirror.isppower.de/.*

- name: "Ensure {{ apt_keyring_dir }} directory exists"
  file:
    path: "{{ apt_keyring_dir }}"
    state: directory
    mode: "755"
    owner: root
    group: root

- name: Add Jenkins GPG key
  ansible.builtin.copy:
    src: jenkins.asc
    dest: "{{ apt_keyring_dir }}/jenkins.asc"
    force: true
    mode: "0644"
    owner: root
    group: root

- name: Add Jenkins APT repository (Debian <12)
  ansible.builtin.apt_repository:
    repo: deb [signed-by={{ apt_keyring_dir }}/jenkins.asc] http://pkg.jenkins-ci.org/debian-stable binary/
    filename: jenkins
    update_cache: yes
  when: ansible_distribution_major_version is version('12', '<')

- name: Add Jenkins repository (Debian >=12)
  ansible.builtin.template:
    src: jenkins.sources.j2
    dest: /etc/apt/sources.list.d/jenkins.sources
    state: present
  register: jenkins_sources
  when: ansible_distribution_major_version is version('12', '>=')

- name: Update APT cache
  ansible.builtin.apt:
    update_cache: yes
  when: jenkins_sources is changed

- name: Install Jenkins
  ansible.builtin.apt:
    name: jenkins
    state: present

- name: Change Jenkins port
  ansible.builtin.replace:
    name: /etc/default/jenkins
    regexp: "^HTTP_PORT=.*$"
    replace: "HTTP_PORT=8081"
  notify: Restart Jenkins
