---
- block:
  - name: Jenkins package repository key
    apt_key: url='{{ jenkins_repo_key }}'

  - name: Install the jenkins stable repository
    apt_repository: repo='{{ jenkins_stable_repo }}' update_cache=yes
    when: not jenkins_use_latest

  - name: Install the jenkins latest repository
    apt_repository: repo='{{ jenkins_latest_repo }}' update_cache=yes
    when: jenkins_use_latest

  - name: Install jenkins
    apt: pkg={{ item }} state={{ jenkins_pkg_state }} update_cache=yes cache_valid_time=3600
    register: jenkins_install
    with_items: '{{ jenkins_packages }}'

  - name: Install some jenkins requirements
    apt: pkg={{ item }} state={{ jenkins_pkg_state }} update_cache=yes cache_valid_time=3600
    with_items: '{{ jenkins_package_requirements }}'

  - name: install sbt launcher
    copy: src={{ item }} dest=/usr/local/lib/{{ item }}
    with_items: '{{ jenkins_sbt_launch_jars }}'

  - name: Set the startup jenkins options
    template: src=jenkins.default.j2 dest=/etc/default/jenkins owner=root group=root mode=0444
    register: jenkins_must_be_restarted

  - name: Start and enable the Jenkins service
    service: name=jenkins state=started enabled=yes
    register: jenkins_has_been_started

  - name: Restart jenkins if the configuration changed
    service: name=jenkins state=restarted
    when: jenkins_must_be_restarted is changed
    register: jenkins_has_been_restarted

  when: jenkins_install
  tags: [ 'jenkins', 'jenkins_master' ]

- block:
    - name: Ensure that jenkins is stoppend and disabled
      service: name=jenkins state=stopped enabled=no

    - name: Remove jenkins
      apt: pkg={{ item }} state=absent
      with_items: '{{ jenkins_packages }}'

    - name: Remove the jenkins stable repository
      apt_repository: repo='{{ jenkins_stable_repo }}' state=absent update_cache=yes

    - name: Remove the jenkins latest repository
      apt_repository: repo='{{ jenkins_latest_repo }}' state=absent update_cache=yes

    - name: Remove the jenkins package repository key
      apt_key: url='{{ jenkins_repo_key }}' state=absent

  when: not jenkins_install
  tags: [ 'jenkins', 'jenkins_master' ]