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

- name: "prerequisites"
  ansible.builtin.apt:
    name:
      - unzip
    update_cache: true
  tags: sonarqube

- name: "group sonarqube"
  ansible.builtin.group:
    name: sonarqube
    system: true
  tags: sonarqube

- name: "user sonarqube"
  ansible.builtin.user:
    name: sonarqube
    group: sonarqube
    system: true
  tags: sonarqube

- name: "folder tree"
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: sonarqube
    group: sonarqube
  loop:
    - "/opt/sonarqube/stateful"
    - "/opt/sonarqube/stateful/logs"
    - "/opt/sonarqube/stateless"
  tags: sonarqube

- name: "Extract sonarqube from {{ sonarqube_download_url }} to /dev/shm"
  ansible.builtin.unarchive:
    src: "{{ sonarqube_download_url }}"
    remote_src: true
    dest: "/dev/shm"
    owner: sonarqube
    group: sonarqube
  tags: sonarqube

- name: "move stateful folders 'data' and 'extensions' if they don't exist"
  ansible.builtin.command: "mv /dev/shm/sonarqube-{{ sonarqube_version }}/{{ item }} /opt/sonarqube/stateful/{{ item }}"
  args:
    creates: "/opt/sonarqube/stateful/{{ item }}"
  loop:
    - data
    - extensions
  tags: sonarqube

- name: "remove stateful folders data, extensions and logs"
  ansible.builtin.file:
    path: "/dev/shm/sonarqube-{{ sonarqube_version }}/{{ item }}"
    state: absent
  loop:
    - data
    - extensions
    - logs
  tags: sonarqube

- name: "symbolic links data, extensions and logs"
  ansible.builtin.file:
    src: "/opt/sonarqube/stateful/{{ item }}"
    dest: "/dev/shm/sonarqube-{{ sonarqube_version }}/{{ item }}"
    state: link
    owner: sonarqube
    group: sonarqube
  loop:
    - data
    - extensions
    - logs
  tags: sonarqube

- name: "put version of sonarqube in VERSION file"
  ansible.builtin.copy:
    content: "{{ sonarqube_version }}"
    dest: "/dev/shm/sonarqube-{{ sonarqube_version }}/VERSION"
    owner: sonarqube
    group: sonarqube
  tags: sonarqube

- name: "make sure /opt/sonarqube/stateless does not exist for now"
  ansible.builtin.file:
    path: "/opt/sonarqube/stateless"
    state: absent
  tags: sonarqube

- name: "move /dev/shm/sonarqube-{{ sonarqube_version }} to /opt/sonarqube/stateless"
  ansible.builtin.command: "mv /dev/shm/sonarqube-{{ sonarqube_version }} /opt/sonarqube/stateless"
  tags: sonarqube

- name: "make sure the folder /opt/sonarqube belongs to the user sonarqube"
  ansible.builtin.file:
    path: "/opt/sonarqube"
    owner: sonarqube
    group: sonarqube
    recurse: true
    state: directory
  tags: sonarqube
