---
# Common-Rolle für grundlegende Systemeinstellungen

- name: Setze globale Variablen
  set_fact:
    deploy_root: "{{ deploy_root | default('/var/www/michaelschiemer') }}"
    deploy_user: "{{ deploy_user | default(ansible_user) }}"
    app_domain: "{{ app_domain | default('localhost') }}"
  tags: [always]

- name: Aktualisiere Paketindex
  apt:
    update_cache: yes
    cache_valid_time: 3600
  tags: [always]

- name: Installiere grundlegende Pakete
  apt:
    name:
      - sudo
      - vim
      - htop
      - git
      - zip
      - unzip
      - curl
      - wget
      - net-tools
      - rsync
      - python3-pip
      - ufw
      - fail2ban
    state: present
  tags: [system, packages]

- name: Setze Zeitzone auf Europe/Berlin
  timezone:
    name: Europe/Berlin
  tags: [system, timezone]

# Benutzer und Berechtigungen
- name: Stelle sicher, dass Deploy-Benutzer existiert
  user:
    name: "{{ deploy_user }}"
    shell: /bin/bash
    groups: sudo
    append: yes
    createhome: yes
    state: present
  when: deploy_user != 'root' and ansible_connection != 'local'
  tags: [system, user]

- name: Stelle sicher, dass SSH-Verzeichnis existiert
  file:
    path: "/home/{{ deploy_user }}/.ssh"
    state: directory
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0700'
  when: deploy_user != 'root' and ansible_connection != 'local'
  tags: [system, user]

- name: Konfiguriere passwordless sudo für deploy-Benutzer
  lineinfile:
    path: "/etc/sudoers.d/{{ deploy_user }}"
    line: "{{ deploy_user }} ALL=(ALL) NOPASSWD: ALL"
    state: present
    create: yes
    mode: '0440'
    validate: 'visudo -cf %s'
  become: true
  when: deploy_user != 'root' and ansible_connection != 'local'
  tags: [system, user]

# Firewall
- name: Öffne Ports in Firewall
  ufw:
    rule: allow
    port: "{{ item }}"
    proto: tcp
  loop:
    - '22'  # SSH
    - '80'  # HTTP
    - '443' # HTTPS
  tags: [system, firewall]

- name: Aktiviere Firewall
  ufw:
    state: enabled
    policy: deny
  tags: [system, firewall]

# Verzeichnisse
- name: Erstelle deploy_root-Verzeichnis
  file:
    path: "{{ deploy_root }}"
    state: directory
    owner: "{{ deploy_user }}"
    group: "{{ deploy_user }}"
    mode: '0755'
  tags: [system, directories]
