# vim: ft=yaml.ansible
# code: language=ansible
---
- name: Copy hosts file
  ansible.builtin.template:
    src: hosts.j2
    dest: /etc/hosts
    owner: root
    group: root
    mode: u=rw,g=r,o=r

- name: Copy MOTD file
  ansible.builtin.template:
    src: motd.j2
    dest: /etc/motd.d/10-ansible
    owner: root
    group: root
    mode: u=rw,g=r,o=r

- name: Add users
  ansible.builtin.user:
    name: "{{ item.name }}"
    comment: "{{ item.comment }}"
    groups: "{{ item.groups }}"
    shell: /bin/bash
    state: present
  loop: "{{ users }}"

- name: Add SSH keys to users
  ansible.posix.authorized_key:
    user: "{{ item.name }}"
    key: "{{ item.ssh_keys | join('\n') }}"
    exclusive: true
  loop: "{{ users }}"

- name: Allow passwordless sudo
  community.general.sudoers:
    name: passwordless
    group: wheel
    host: ALL
    commands: ALL
    nopassword: true
    state: present

- name: Copy sshd_config
  ansible.builtin.copy:
    src: sshd_config
    dest: /etc/ssh/sshd_config
    owner: root
    group: root
    mode: u=rw,g=r,o=r
    validate: /usr/sbin/sshd -t -f %s
  notify: Restart sshd

- name: Enable extra repositories
  ansible.builtin.dnf:
    name:
      - epel-release
      - rocky-release-security
    state: present
  notify: Upgrade system packages

- name: Install system packages
  ansible.builtin.dnf:
    name:
      - bind-utils
      - firewalld
      - htop
      - jq
      - logrotate
      - lsof
      - mtr
      - rsyslog
      - telnet
      - vim
    update_cache: true
    state: present

- name: Ensure services are enabled and running
  ansible.builtin.service:
    name: "{{ item }}"
    enabled: true
    state: started
  loop:
    - firewalld
    - rsyslog

- name: Services for non-LXC instances
  when: instance_type != 'lxc'
  block:
    - name: Install haveged
      ansible.builtin.dnf:
        name: haveged
        state: present

    - name: Ensure haveged is enabled and running
      ansible.builtin.service:
        name: haveged
        enabled: true
        state: started

- name: Services for QEMU instances
  when: instance_type == 'qemu'
  block:
    - name: Ensure fstrim systemd timer is enabled
      ansible.builtin.systemd_service:
        name: fstrim.timer
        enabled: true
        state: started

- name: Create directory '{{ data_fs }}'
  ansible.builtin.file:
    path: "{{ data_fs }}"
    owner: root
    group: root
    mode: u=rwx,g=rx,o=rx
    seuser: system_u
    serole: object_r
    setype: unlabeled_t
    selevel: s0
    state: directory
  when: instance_type == 'vps'

- name: Configure firewall
  ansible.builtin.import_tasks: firewall.yml