---
-
  name: "Set SDKMAN user/group vars"
  ansible.builtin.set_fact:
    service_user: '{{ service_user | default(ansible_user_id) }}'
    service_group: '{{ service_group | default(ansible_user_gid) }}'

-
  name: "Including system vars"
  ansible.builtin.include_vars: "{{ lookup('first_found', params) }}"
  vars:
    params:
      files:
        - '{{ ansible_distribution }}.yml'
        - '{{ ansible_os_family }}.yml'
        - default.yml
      paths:
        - vars

-
  name: "Installing system packages"
  ansible.builtin.package:
    name: '{{ system_packages }}'
    use: '{{ ansible_pkg_mgr }}'
    state: present
  become: true
  tags:
    - sdkman_privilege

-
  name: "Creating Ansible Temp Directory"
  become: true
  ansible.builtin.file:
    mode: '0777'
    path: "{{ item }}"
    state: directory
    owner: '{{ service_user }}'
    group: '{{ service_group }}'
  with_items:
    - "{{ service_home_dir }}/.ansible/tmp"

-
  name: "Setting SDKMAN_DIR environment variable"
  ansible.builtin.set_fact:
    sdkman_dir: '{{ sdkman_dir | default(service_home_dir + "/.sdkman") }}'

-
  name: "Checking for SDKMAN installation"
  ansible.builtin.stat:
    path: '{{ sdkman_dir }}/bin/sdkman-init.sh'
  register: sdkman_init

-
  name: "Downloading SDKMAN"
  when: not sdkman_init.stat.exists
  become: '{{ service_user != ansible_user_id }}'
  become_user: '{{ service_user }}'
  block:
    -
      name: "Downloading SDKMAN"
      become: true
      ansible.builtin.get_url:
        mode: '0755'
        url: https://get.sdkman.io
        dest: '{{ sdkman_tmp_dir }}/sdkman_script'
        owner: '{{ service_user }}'
        group: '{{ service_group }}'
        validate_certs: '{{ sdkman_validate_ssl }}'

    -
      name: "Running SDKMAN script"
      environment:
        SDKMAN_DIR: '{{ sdkman_dir }}'
      ansible.builtin.command: /bin/bash {{ sdkman_tmp_dir }}/sdkman_script
      args:
        creates: '{{ sdkman_dir }}/bin/sdkman-init.sh'
      notify: Cleanup SDKMAN script

-
  name: "Fixing permissions on SDKMAN_DIR"
  ansible.builtin.file:
    path: '{{ sdkman_dir }}'
    state: directory
    owner: '{{ service_user }}'
    group: '{{ service_group }}'
    recurse: true
  become: true
  tags:
    - sdkman_privilege
