---
# file: roles/sonarqube/tasks/main.yml

- name: "check if the folder /opt/sonarqube/stateless exists"
  ansible.builtin.stat:
    path: "/opt/sonarqube/stateless"
  register: folder_sonarqube
  tags: sonarqube

- name: "check if sonarqube update is needed"
  block:
    - name: "check version of sonarqube"
      ansible.builtin.slurp:
        src: "/opt/sonarqube/stateless/VERSION"
      register: sonarqube_current
    - name: "set fact current_sonarqube_version"
      ansible.builtin.set_fact:
        current_sonarqube_version: "{{ sonarqube_current['content'] | b64decode | trim }}"
    - name: "check if sonarqube update is needed"
      ansible.builtin.debug:
        msg: "Update needed, from {{ current_sonarqube_version }} to {{ sonarqube_version }} (use: --extra-vars '{ \"sonarqube_update_sonarqube_now\" : true}')"
      when: current_sonarqube_version != sonarqube_version
  when: folder_sonarqube.stat.exists
  tags: sonarqube

- name: "stop sonarqube?"
  ansible.builtin.service:
    name: sonarqube
    state: stopped
  when:
    - folder_sonarqube.stat.exists
    - sonarqube_update_sonarqube_now
    - current_sonarqube_version != sonarqube_version
  tags: sonarqube

- name: "install or update sonarqube"
  ansible.builtin.import_tasks: install_sonarqube.yml
  when: (not folder_sonarqube.stat.exists) or (folder_sonarqube.stat.exists and sonarqube_update_sonarqube_now and current_sonarqube_version != sonarqube_version)
  tags: sonarqube

- name: "configure"
  ansible.builtin.import_tasks: configure.yml
  tags: sonarqube

- name: "install or update sonarqube plugins"
  ansible.builtin.import_tasks: install_plugins.yml
  tags: sonarqube

- name: "/etc/systemd/system/sonarqube.service"
  ansible.builtin.template:
    src: "sonarqube.service.j2"
    dest: "/etc/systemd/system/sonarqube.service"
  notify:
    - systemctl daemon_reload
    - restart sonarqube
  tags: sonarqube

- name: "systemd enabled and started"
  ansible.builtin.systemd:
    name: sonarqube.service
    state: started
    enabled: true
  tags: sonarqube
