---
# Custom user implies multiple changes and requires additional parameters to be set

- name: "Custom user : Service group presence"
  # Create a group for custom user
  become: true
  notify: Service restart
  ansible.builtin.group:
    name: "{{ agent_service_group }}"
    gid: "{{ agent_service_gid | default(omit) }}"
    state: present
  tags: [deploy]

- name: "Custom user : Service user presence"
  become: true
  notify: Service restart
  ansible.builtin.user:
    name: "{{ agent_service_user }}"
    group: "{{ agent_service_group }}"
    uid: "{{ agent_service_uid | default(omit) }}"
    system: true
    shell: /usr/sbin/nologin
    home: "{{ agent_service_user_home }}"
    create_home: true
    state: present
  tags: [deploy]

- name: "Custom user : Separate Log folder & permissions"
  # Custom user requires custom folder ownership to manage logs(create/write/rotate)
  become: true
  notify: Service restart
  ansible.builtin.file:
    path: "{{ item.folder | dirname }}"
    state: directory
    owner: "{{ agent_service_user }}"
    group: "{{ agent_service_group }}"
    setype: "{{ item.setype }}"
    recurse: true
  loop: "{{ agent_internal_file_loop | select }}"
  vars:
    agent_internal_file_loop:
      - { folder: "{{ agent_param_logfile | default(None) }}", setype: "{{ agent_folder_log_setype | default(None) }}" }
      # - {folder: '{{ agent_param_pidfile | default(None) }}', setype: '{{ agent_folder_pid_setype | default(None) }}'}
  tags: [deploy]

- name: "Custom user : Systemd : Custom user override in service file"
  # changing user requires to change permissions on pid file and folder.
  #
  # currently packages use not the best approach to manage pid location by setting all at: /usr/lib/tmpfiles.d/zabbix-agent.conf
  # which creates folder on systemd start even with agentd service disabled. (subject to change in future)
  #
  # to avoid conflict with different zabbix components we are changing location only for current service at systemd level in unit zabbix_agent.service file.
  # which is done using overrides at etc, instead of changes on tmpfs mount.
  #
  # same applies to log file and folder
  become: true
  notify:
    - Reload systemd daemon
    - Service restart
  ansible.builtin.blockinfile:
    path: "{{ agent_systemd_override_path }}"
    marker: "###<!-- {mark} ansible managed block -->##"
    block: |
      [Service]
      User={{ agent_service_user }}
      Group={{ agent_service_group }}
      RuntimeDirectory={{ agent_binary_name }}
      PIDFile={{ agent_param_pidfile }}
    state: present
    create: true
    mode: "{{ agent_conf_file.folder_permissions.mode }}"
    owner: "{{ agent_conf_file.permissions.user }}"
    group: "{{ agent_conf_file.permissions.group }}"
  tags: [deploy, config]
