---
# file: roles/coraza/tasks/main.yml

- name: "ensure coraza group exists"
  ansible.builtin.group:
    name: coraza
  tags: coraza

- name: "ensure coraza user exists"
  ansible.builtin.user:
    name: coraza
    group: coraza
    system: true
    create_home: false
  tags: coraza

- name: "build coraza-spoa binary"
  ansible.builtin.command: /usr/local/go/bin/go run mage.go build
  args:
    chdir: /usr/local/src/coraza-spoa
  tags: coraza

- name: "ensure main coraza directory exist"
  ansible.builtin.file:
    path: /etc/coraza
    state: directory
  tags: coraza

- name: "ensure main coraza configuration files are present"
  ansible.builtin.template:
    src: "{{ item }}.j2"
    dest: "/etc/coraza/{{ item }}"
  notify: restart coraza
  loop:
    - config.yaml
    - coraza.conf
  tags: coraza

- name: "ensure coraza binary is installed in /usr/local/bin"
  ansible.builtin.copy:
    src: /usr/local/src/coraza-spoa/build/coraza-spoa
    dest: /usr/local/bin/coraza-spoa
    remote_src: true
    mode: 755
  tags: coraza

- name: "ensure crs configuration file exists"
  ansible.builtin.copy:
    src: /usr/local/src/coreruleset/crs-setup.conf.example
    dest: /etc/coraza/crs-setup.conf
    remote_src: true
  notify: restart coraza
  tags: coraza

- name: "ensure crs rules and plugins directories are present"
  ansible.builtin.copy:
    src: "/usr/local/src/coreruleset/{{ item }}"
    dest: "/etc/coraza/{{ item }}"
    remote_src: true
  loop:
    - rules
    - plugins
  tags: coraza

- name: "ensure coraza spoa service systemd file exists"
  ansible.builtin.copy:
    src: coraza-spoa.service
    dest: /etc/systemd/system/coraza-spoa.service
  tags: coraza

- name: "[always] coraza service started and enabled"
  ansible.builtin.systemd_service:
    name: coraza-spoa
    state: started
    enabled: true
  tags: coraza
