---

# Install plugins
# inspired by https://github.com/geerlingguy/ansible-role-jenkins MIT (Expat) / BSD)
# but we couldn't use jenkins_plugin's Ansible module because of crumb (CSRF) problems with our version

# Get current plugin list
# Warning : it may not be up to date if Jenkins hasn't been restarted after last plugin install
- name: Get the current plugin list
  shell: "{{ jenkins_cli_command }} list-plugins | awk '{ print $1 }'"
  changed_when: False
  check_mode: no
  register: current_plugin_list

## Update Jenkins so that plugin updates don't fail.
#- name: Create Jenkins updates directory.
#  file:
#    path: "{{ jenkins_home }}/updates"
#    state: directory
#    owner: jenkins
#    group: jenkins
#
#- name: Download current plugin updates from Jenkins update site.
#  get_url:
#    url: "{{ jenkins_updates_url }}/update-center.json"
#    dest: "{{ jenkins_home }}/updates/default.json"
#    owner: jenkins
#    group: jenkins
#    mode: 0440
#  changed_when: false
#  register: get_result
#  until: get_result is success
#  retries: 3
#  delay: 2
#
#- name: Remove first and last line from json file.
#  replace:
#    path: "{{ jenkins_home }}/updates/default.json"
#    regexp: "1d;$d"

- name: Install Jenkins plugins.
  shell: "{{ jenkins_cli_command }} install-plugin {{ item | quote }}"
  with_items: "{{ jenkins_plugins }}"
  when: item not in current_plugin_list.stdout_lines
  notify: safe-restart jenkins and wait

- name: Install system packages needed by Jenkins plugins
  apt:
    name: "{{ jenkins_plugins_system_dependency }}"
    state: present