- name: Check if required vars are set
  ansible.builtin.fail:
    msg: "Required variables are not set for Podman setup. Please check your playbook variables.)"
  when:
    - podman_user is not defined
    - podman_group is not defined
    - podman_user_home is not defined

- name: Create group
  become: true
  ansible.builtin.group:
    name: "{{ podman_group }}"
    system: true

- name: Create user
  become: true
  ansible.builtin.user:
    name: "{{ podman_user }}"
    groups: "{{ podman_extra_groups | default([]) }}"
    shell: /bin/bash
    home: "{{ podman_user_home }}"
    group: "{{ podman_group }}"

- name: Disable password login for user
  ansible.builtin.command: passwd -d "{{ podman_user }}"
  become: true
  changed_when: false

- name: Create user home
  become: true
  ansible.builtin.file:
    path: "{{ podman_user_home }}"
    state: directory
    owner: "{{ podman_user }}"
    group: "{{ podman_group }}"
    mode: "0750"

- name: Create build folders
  become: true
  ansible.builtin.file:
    path: "{{ podman_user_home }}/build"
    state: directory
    owner: "{{ podman_user }}"
    group: "{{ podman_group }}"
    mode: "0750"

- name: Create folders
  become: true
  ansible.builtin.file:
    path: "{{ podman_user_home }}/{{ item }}"
    state: directory
    owner: "{{ podman_user }}"
    group: "{{ podman_group }}"
    mode: "0750"
  loop: "{{ podman_user_folders }}"

- name: "Add SSH Authorized key"
  become: true
  ansible.posix.authorized_key:
    user: "{{ podman_user }}"
    key: "{{ podman_user_pubkey }}"
    state: "{{ 'present' if podman_user_pubkey is defined else 'absent' }}"
  when: podman_user_pubkey is defined and podman_user_pubkey != ""

- name: SELinux tasks (RedHat only)
  when: ansible_os_family == 'RedHat'
  become: true
  block:
    - name: Persistently set SELinux context
      community.general.sefcontext:
        target: "{{ podman_user_home }}(/.*)?"
        setype: user_home_dir_t
        state: present

    - name: Persistently set SELinux context (ssh authorized keys)
      community.general.sefcontext:
        target: "{{ podman_user_home }}/.ssh/authorized_keys"
        setype: ssh_home_t
        state: present
      when: podman_user_pubkey is defined and podman_user_pubkey != ""

    - name: Apply SELinux context
      ansible.builtin.command: restorecon -Rv {{ podman_user_home }}
      changed_when: false
