---
- name: Create Alertmanager Directories
  become: yes
  become_user: jingrow
  file:
    path: "{{ item }}"
    state: directory
    mode: 0755
  with_items:
    - /home/jingrow/alertmanager
    - /home/jingrow/alertmanager/data
    - /home/jingrow/.config/amtool

- name: Set Architecture
  set_fact:
    arch: "{{'amd64' if (ansible_architecture == 'x86_64') else 'arm64'}}"

- name: Download Alertmanager Archive
  become: yes
  become_user: jingrow
  unarchive:
    src: "https://github.com/prometheus/alertmanager/releases/download/v0.27.0/alertmanager-0.27.0.linux-{{ arch }}.tar.gz"
    dest: /tmp
    remote_src: yes

- name: Copy Alertmanager and Amtool Binaries
  become: yes
  become_user: jingrow
  copy:
    src: "/tmp/alertmanager-0.27.0.linux-{{ arch }}/{{ item }}"
    dest: "/home/jingrow/alertmanager/{{ item }}"
    mode: 0755
    remote_src: yes
  with_items:
    - alertmanager
    - amtool

- name: Create Amtool Config
  become: yes
  become_user: jingrow
  template:
    src: amtool.yml
    dest: /home/jingrow/.config/amtool/config.yml
    mode: 0644

- name: Configure Alertmanager
  template:
    src: alertmanager.yml
    dest: /home/jingrow/alertmanager/alertmanager.yml
    validate: "/home/jingrow/alertmanager/amtool check-config %s"

- name: Configure ownership permissions on alertmanager.yml
  file:
    path: /home/jingrow/alertmanager/alertmanager.yml
    owner: jingrow
    group: jingrow
    mode: 0600

- name: Create Alertmanager Systemd Service File
  template:
    src: alertmanager.service
    dest: /etc/systemd/system/alertmanager.service
    owner: root
    group: root
    mode: 0644

- name: Restart Alertmanager Service
  systemd:
    daemon_reload: true
    name: alertmanager
    enabled: yes
    state: restarted
