---
# Playbook 02: System Setup
# Install packages, configure firewall and security

- name: System Setup
  hosts: all
  become: yes
  
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Upgrade all packages
      apt:
        upgrade: dist
        autoremove: yes
        autoclean: yes

    - name: Install essential packages
      apt:
        name:
          - curl
          - wget
          - git
          - vim
          - htop
          - net-tools
          - dnsutils
          - ufw
          - fail2ban
          - unattended-upgrades
          - apt-transport-https
          - ca-certificates
          - gnupg
          - lsb-release
          - software-properties-common
          - python3-pip
          - python3-docker
          - rsync
          - "{% if install_rclone %}rclone{% endif %}"
        state: present

    - name: Configure UFW - Allow SSH
      ufw:
        rule: allow
        port: '22'
        proto: tcp

    - name: Configure UFW - Allow HTTP
      ufw:
        rule: allow
        port: '80'
        proto: tcp

    - name: Configure UFW - Allow HTTPS TCP
      ufw:
        rule: allow
        port: '443'
        proto: tcp

    - name: Configure UFW - Allow HTTPS UDP (HTTP/3)
      ufw:
        rule: allow
        port: '443'
        proto: udp

    - name: Configure UFW - Allow Tailscale
      ufw:
        rule: allow
        port: '41641'
        proto: udp

    - name: Enable UFW
      ufw:
        state: enabled
        policy: deny

    - name: Configure fail2ban for SSH
      copy:
        dest: /etc/fail2ban/jail.local
        content: |
          [sshd]
          enabled = true
          port = ssh
          filter = sshd
          logpath = /var/log/auth.log
          maxretry = 5
          bantime = 600
      notify: restart fail2ban

    - name: Enable unattended security updates
      copy:
        dest: /etc/apt/apt.conf.d/20auto-upgrades
        content: |
          APT::Periodic::Update-Package-Lists "1";
          APT::Periodic::Unattended-Upgrade "1";
          APT::Periodic::AutocleanInterval "7";

    - name: Set timezone
      timezone:
        name: "{{ timezone }}"

    - name: Set kernel parameters for Docker
      sysctl:
        name: "{{ item.key }}"
        value: "{{ item.value }}"
        state: present
        reload: yes
      loop:
        - { key: 'net.ipv4.ip_forward', value: '1' }
        - { key: 'fs.inotify.max_user_watches', value: '524288' }

  handlers:
    - name: restart fail2ban
      service:
        name: fail2ban
        state: restarted
