---

- name: Copy server dotfiles
  tags: [dotfiles, dotfiles:server]
  ansible.builtin.copy:
    src: "{{ playbook_dir }}/../dotfiles/server/{{ item.src }}"
    dest: "{{ user_home }}/{{ item.dest }}"
    owner: "{{ username }}"
    group: "{{ user_group }}"
    mode: "{{ item.mode }}"
  loop: "{{ server_dotfiles | default([]) }}"
  loop_control:
    label: "{{ item.dest }}"

- name: Render server templates
  tags: [dotfiles, dotfiles:server]
  ansible.builtin.template:
    src: "{{ item.src }}"
    dest: "{{ user_home }}/{{ item.dest }}"
    owner: "{{ username }}"
    group: "{{ user_group }}"
    mode: "{{ item.mode }}"
  loop: "{{ server_templates | default([]) }}"
  loop_control:
    label: "{{ item.dest }}"

- name: Disable SSH root login on server
  tags: [services]
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^\s*PermitRootLogin\s+'
    line: "PermitRootLogin {{ server_sshd_settings.PermitRootLogin }}"
    state: present
    validate: "sshd -t -f %s"
  notify: Reload SSH service

- name: Restrict SSH login to allowed users on server
  tags: [services]
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^\s*AllowUsers\s+'
    line: "AllowUsers {{ server_sshd_allow_users | join(' ') }}"
    state: present
    validate: "sshd -t -f %s"
  notify: Reload SSH service
  when: (server_sshd_allow_users | default([])) | length > 0

- name: Apply server UFW rules
  tags: [services, packages]
  community.general.ufw:
    rule: "{{ item.rule }}"
    name: "{{ item.name | default(omit) }}"
    port: "{{ item.port | default(omit) }}"
    proto: "{{ item.proto | default(omit) }}"
  loop: "{{ server_ufw_rules | default([]) }}"
  loop_control:
    label: "{{ item.name | default(item.port) }}"

- name: Enable UFW firewall on server
  tags: [services, packages]
  community.general.ufw:
    state: enabled
