---
# systemd service hardening for chatmail monitoring stack.
# Deploys drop-in override files that reduce systemd-analyze security
# scores from ~9.6 to 1.3–1.9 across all services.

- name: Create systemd override directories
  file:
    path: "/etc/systemd/system/{{ item }}.service.d"
    state: directory
    owner: root
    group: root
    mode: "0755"
  loop: "{{ chatmail_hardened_services }}"

- name: Deploy hardening drop-ins
  copy:
    src: "{{ item }}-hardening.conf"
    dest: "/etc/systemd/system/{{ item }}.service.d/hardening.conf"
    owner: root
    group: root
    mode: "0644"
  loop: "{{ chatmail_hardened_services }}"
  notify: reload and restart hardened services

- name: Verify security scores
  shell: |
    set -euo pipefail
    score=$(systemd-analyze security {{ item }} 2>/dev/null | grep 'Overall exposure' | awk '{print $NF}')
    echo "{{ item }}: ${score}"
    # Fail if score is above 3.0 (our target is under 2.0, allow margin)
    awk "BEGIN{if(${score}+0 > 3.0) exit 1}"
  args:
    executable: /bin/bash
  changed_when: false
  loop: "{{ chatmail_hardened_services }}"
  tags: [verify]
