---
- name: Include optimization tasks
  include_tasks: optimization.yaml
  tags: optimization

- name: Install essential packages
  ansible.builtin.apt:
    name: "{{ system_packages.essential }}"
    state: present
    update_cache: true
    cache_valid_time: 3600
  tags: packages

- name: Set hostname and FQDN
  block:
    - name: Set hostname
      ansible.builtin.hostname:
        name: "{{ hostname | default(inventory_hostname) }}"

    - name: Configure FQDN in hosts file
      ansible.builtin.lineinfile:
        path: /etc/hosts
        regexp: '^127\.0\.1\.1.*'
        line: "127.0.1.1 {{ fqdn | default(hostname) }} {{ hostname | default(inventory_hostname) }}"
        state: present
  tags: system

- name: Deploy MOTD template
  template:
    src: motd.j2
    dest: /etc/motd
    mode: '0644'

- name: Configure timezone
  community.general.timezone:
    name: "{{ timezone }}"
  tags: system, ntp

- name: Install and configure NTP
  include_role:
    name: geerlingguy.ntp
  tags: system, ntp

- name: Deploy SSH configuration
  ansible.builtin.template:
    src: sshd_config.j2
    dest: /etc/ssh/sshd_config
    owner: root
    group: root
    mode: '0600'
    validate: '/usr/sbin/sshd -t -f %s'
  notify: Restart ssh

- name: Create admin users with proper SSH keys
  block:
    - name: Ensure user exists
      ansible.builtin.user:
        name: "{{ item.name }}"
        shell: "{{ item.shell | default('/bin/bash') }}"
        groups: "{{ item.groups }}"
        append: true
        state: "{{ item.state | default('present') }}"
        create_home: true
        home: "/home/{{ item.name }}"
      loop: "{{ admin_users }}"
      tags: users

    - name: Deploy SSH authorized keys
      ansible.posix.authorized_key:
        user: "{{ item.0.name }}"
        state: present
        key: "{{ item.1 }}"
        manage_dir: true
      with_subelements:
        - "{{ admin_users }}"
        - ssh_keys
      tags: users, ssh
