---
- name: Create Grafana Directories
  become: yes
  become_user: jingrow
  file:
    path: "{{ item }}"
    state: directory
    mode: 0755
  with_items:
    - /home/jingrow/grafana
    - /home/jingrow/grafana/provisioning
    - /home/jingrow/grafana/provisioning/datasources
    - /home/jingrow/grafana/provisioning/dashboards
    - /home/jingrow/grafana/logs
    - /home/jingrow/grafana/data
    - /home/jingrow/grafana/data/dashboards
    - /home/jingrow/grafana/data/plugins

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

- name: Download Grafana Archive
  become: yes
  become_user: jingrow
  unarchive:
    src: "https://dl.grafana.com/oss/release/grafana-12.2.1.linux-{{ arch }}.tar.gz"
    dest: /tmp
    remote_src: yes

- name: Copy Grafana Directories
  become: yes
  become_user: jingrow
  copy:
    src: "/tmp/grafana-12.2.1/{{ item }}/"
    dest: "/home/jingrow/grafana/{{ item }}/"
    mode: 0755
    remote_src: yes
  with_items:
    - bin
    - conf
    - plugins-bundled
    - public

- name: Provision Prometheus Datasource
  become: yes
  become_user: jingrow
  template:
    src: prometheus.yml
    dest: /home/jingrow/grafana/provisioning/datasources/prometheus.yml
    mode: 0640

- name: Configure Grafana
  become: yes
  become_user: jingrow
  template:
    src: grafana.ini
    dest: /home/jingrow/grafana/grafana.ini
    mode: 0640

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

- name: Restart Grafana Service
  systemd:
    daemon_reload: true
    name: grafana
    enabled: yes
    state: restarted

- name: Setup Grafana Authentication
  become: yes
  become_user: jingrow
  command: "htpasswd -Bbc /home/jingrow/agent/nginx/grafana.htpasswd jingrow {{ grafana_password }}"

- name: Setup Grafana HTTP Authentication
  become: yes
  become_user: jingrow
  command: "htpasswd -Bbc /home/jingrow/agent/nginx/grafana-ui.htpasswd admin {{ grafana_password }}"

- name: Setup Agent NGINX
  become: yes
  become_user: jingrow
  command: /home/jingrow/agent/env/bin/agent setup nginx
  args:
    chdir: /home/jingrow/agent
