---

- block:
  - name: Copy bamboo JAR from Bamboo Server
    get_url:
      url: "{{bamboo_server_url}}/agentInstaller/{{bamboo_agent_jar}}"
      dest: "/home/{{bamboo_user}}/{{bamboo_agent_jar}}"
      owner: zoox
      group: zoox
      mode: 0644

  - name: Check if Upstart Bamboo Service Exists
    stat:
      path: /etc/init/bamboo.conf
    register: bamboo_upstart_status

  - name: Check if Systemd Bamboo Service Exists
    stat:
      path: /etc/systemd/system/bamboo.service
    register: bamboo_systemd_status

  - name: Stop existing bamboo service
    service:
      name: bamboo
      state: stopped
    when: bamboo_upstart_status.stat.exists or bamboo_systemd_status.stat.exists

  - name: register Bamboo service definition (Upstart)
    template:
      src: bamboo.conf
      dest: /etc/init/bamboo.conf
      mode: 0755
      owner: root
      group: root
    when: ansible_service_mgr == "upstart"

  - name: register Bamboo service definition (Systemd)
    template:
      src: bamboo.service
      dest: /etc/systemd/system/bamboo.service
      mode: 0644
      owner: root
      group: root
    when: ansible_service_mgr == "systemd"

  - set_fact:
      bamboo_config: /home/{{bamboo_user}}/bamboo-agent-home/bamboo-agent.cfg.xml
      agent_name: "{{ inventory_hostname }}"

  - name: Create Bamboo config directory
    file:
      path: "{{ bamboo_config | dirname }}"
      state: directory
      mode: 0755
      owner: "{{ bamboo_user }}"
      group: "{{ bamboo_user }}"

  - name: Install bamboo agent config file
    template:
      src: bamboo-agent.cfg.xml
      dest: "{{ bamboo_config }}"
      mode: 0644
      owner: "{{ bamboo_user }}"
      group: "{{ bamboo_user }}"
      force: no

  - name: Update agent name
    lineinfile:
      path: "{{ bamboo_config }}"
      line: "    <name>{{ agent_name }}</name>"
      regexp: ".*<name>.*</name>.*"
      state: present

  - name: Update agent description
    lineinfile:
      path: "{{ bamboo_config }}"
      line: "    <description>Remote bamboo agent for {{ agent_name }} on {{ inventory_hostname }}</description>"
      regexp: ".*<description>.*</description>.*"
      state: present

  - name: Start bamboo
    service:
      name: bamboo
      state: started
      enabled: yes

  - name: Confirm agent registration
    wait_for:
      path: "{{ bamboo_config }}"
      search_regex: '<id>.*</id>'
      timeout: 90

  become: yes
