---
- name: Ensure group 'sambausers' exists
  group:
    name: sambausers
    state: present

- name: Ensure configured users are added to the 'sambausers' group
  user:
    append: true
    groups:
      - sambausers
    name: "{{ user.username }}"
  loop: "{{ user_configs }}"
  loop_control:
    label: "{{ user.username }}"
    loop_var: user
  when: user.samba_user | default(false)

- name: Configure Samba file/printer sharing
  blockinfile:
    path: "{{ samba_config }}"
    marker: "# {mark} ANSIBLE MANAGED BLOCK FOR PRINTER/FILE SHARING"
    block: |
      [global]
        allow hosts = {{ samba_allowed_hosts }}
        {% if samba_printers %}
        load printers = yes
        {% endif %}
        # Allows users without accounts to log in and be assigned to the guest account
        map to guest = bad user
        netbios name = {{ samba_netbios_name }}
        obey pam restrictions = yes
        # Source: https://wiki.archlinux.org/index.php/CUPS/Printer_sharing
        printing = CUPS
        proxy = no
        security = user
        server role = standalone server
        server string = Samba on %L
        # Required for allowing wide links (symlinks)
        unix extension = no
        # Follow symlinks out of the current share
        wide links = yes
        workgroup = {{ samba_workgroup }}
      {% for share in (samba_shares | default([])) %}
      [{{ share.id }}]
        browsable = yes
        comment = {{ share.comment }}
        follow symlinks = {{ share.follow_symlinks | default('no') }}
        guest only = {{ share.public | default('yes') }}
        path = {{ share.path }}
        public = {{ share.public | default('no') }}
      {% if share.users is defined %}
        valid users = {{ share.users }}
      {% endif %}
        writable = {{ share.writable | default('no') }}
      {% endfor %}
      {% if samba_printers %}
      [printers]
        browsable = yes
        comment = Printers
        path = /var/spool/samba/
        printable = yes
        public = yes
        writable = no
      [print$]
        browsable = yes
        comment = Printer drivers
        path = /var/lib/samba/printers
        public = yes
        writable = no
      {% for printer in (samba_printers | default([])) %}
      [{{ printer.id }}]
        comment = {{ printer.comment }}
        path = /var/spool/samba/
        printable = yes
        # Source: https://wiki.samba.org/index.php/Setting_up_Samba_as_a_Print_Server
        printer name = {{ printer.name }}
        public = {{ printer.public | default('yes') }}
        writable = no
      {% endfor %}
      {% endif %}
  when:
    - samba_allowed_hosts is defined
    - samba_netbios_name is defined
    - samba_workgroup is defined
    - (samba_shares is defined) or (samba_printers is defined)
