---
- name: Set hostname
  ansible.builtin.hostname:
    name: "{{ inventory_hostname }}"

- name: Set timezone
  community.general.timezone:
    name: "{{ timezone }}"

- name: Enable EPEL repository
  ansible.builtin.dnf:
    name: epel-release
    state: present

- name: Upgrade all packages
  ansible.builtin.dnf:
    name: "*"
    state: latest
    update_cache: true
  tags: update
  notify: Reboot if kernel updated

- name: Install base packages
  ansible.builtin.dnf:
    name: "{{ base_packages }}"
    state: present

- name: Enable and start chrony
  ansible.builtin.systemd:
    name: chronyd
    enabled: true
    state: started

- name: Create ansible group
  ansible.builtin.group:
    name: "{{ ansible_service_user }}"
    state: present

- name: Create ansible user
  ansible.builtin.user:
    name: "{{ ansible_service_user }}"
    group: "{{ ansible_service_user }}"
    groups: wheel
    shell: /bin/bash
    create_home: true
    state: present

- name: Allow ansible user passwordless sudo
  ansible.builtin.copy:
    dest: /etc/sudoers.d/ansible
    content: "{{ ansible_service_user }} ALL=(ALL) NOPASSWD:ALL\n"
    mode: '0440'
    validate: /usr/sbin/visudo -cf %s

- name: Set up SSH authorized key for ansible user
  ansible.posix.authorized_key:
    user: "{{ ansible_service_user }}"
    key: "{{ lookup('file', '~/.ssh/id_ed25519.pub') }}"
    state: present

- name: Harden sshd
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
    state: present
  loop:
    - { regexp: '^#?PermitRootLogin', line: 'PermitRootLogin no' }
    - { regexp: '^#?PasswordAuthentication', line: 'PasswordAuthentication no' }
    - { regexp: '^#?X11Forwarding', line: 'X11Forwarding no' }
  notify: Restart sshd
