---
- name: Build agent binary for linux/arm64
  ansible.builtin.command:
    cmd: go build -o {{ role_path }}/files/morz-agent ./cmd/agent
    chdir: "{{ playbook_dir }}/../player/agent"
  environment:
    GOOS: linux
    GOARCH: arm64
  delegate_to: localhost
  changed_when: true

- name: Ensure signage user exists
  ansible.builtin.user:
    name: "{{ signage_user }}"
    create_home: true
    state: present
  become: true

- name: Ensure config directory exists
  ansible.builtin.file:
    path: "{{ signage_config_dir }}"
    state: directory
    owner: root
    group: root
    mode: "0755"
  become: true

- name: Deploy agent config
  ansible.builtin.template:
    src: config.json.j2
    dest: "{{ signage_config_dir }}/config.json"
    owner: root
    group: "{{ signage_user }}"
    mode: "0640"
  become: true
  notify: Restart morz-agent

- name: Deploy agent binary
  ansible.builtin.copy:
    src: morz-agent
    dest: "{{ signage_binary_dest }}"
    owner: root
    group: root
    mode: "0755"
  become: true
  notify: Restart morz-agent

- name: Deploy systemd unit
  ansible.builtin.template:
    src: morz-agent.service.j2
    dest: /etc/systemd/system/morz-agent.service
    owner: root
    group: root
    mode: "0644"
  become: true
  notify:
    - Reload systemd
    - Restart morz-agent

- name: Ensure journald drop-in directory exists
  ansible.builtin.file:
    path: /etc/systemd/journald.conf.d
    state: directory
    owner: root
    group: root
    mode: "0755"
  become: true

- name: Configure journald volatile storage (RAM only, schont SD-Karte)
  ansible.builtin.copy:
    dest: /etc/systemd/journald.conf.d/morz-volatile.conf
    content: |
      [Journal]
      Storage=volatile
      RuntimeMaxUse=20M
    owner: root
    group: root
    mode: "0644"
  become: true
  notify: Restart journald

- name: Enable and start morz-agent
  ansible.builtin.systemd:
    name: morz-agent
    enabled: true
    state: started
    daemon_reload: false
  become: true
