---
# cold-start-monitor role
# 管理 110 上 read-only 全站 cold-start monitor。

- name: "cold-start monitor | 確認目錄存在"
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: "{{ cold_start_monitor_user }}"
    group: "{{ cold_start_monitor_user }}"
    mode: "0755"
  loop:
    - "{{ cold_start_monitor_script_dir }}"
    - "{{ cold_start_monitor_textfile_dir }}"
    - "{{ cold_start_monitor_log_dir }}"
  tags: cold_start_monitor

- name: "cold-start monitor | 安裝 gate 腳本"
  ansible.builtin.copy:
    src: "{{ cold_start_monitor_check_src }}"
    dest: "{{ cold_start_monitor_script_dir }}/full-stack-cold-start-check.sh"
    owner: "{{ cold_start_monitor_user }}"
    group: "{{ cold_start_monitor_user }}"
    mode: "0755"
  tags: cold_start_monitor

- name: "cold-start monitor | 安裝 textfile 匯出器"
  ansible.builtin.copy:
    src: "{{ cold_start_monitor_exporter_src }}"
    dest: "{{ cold_start_monitor_script_dir }}/cold-start-textfile-exporter.sh"
    owner: "{{ cold_start_monitor_user }}"
    group: "{{ cold_start_monitor_user }}"
    mode: "0755"
  tags: cold_start_monitor

- name: "cold-start monitor | 安裝 cron"
  ansible.builtin.cron:
    name: "AWOOOI cold-start monitor"
    user: "{{ cold_start_monitor_user }}"
    minute: "{{ cold_start_monitor_cron_minute }}"
    job: >-
      PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
      CHECK_SCRIPT={{ cold_start_monitor_script_dir }}/full-stack-cold-start-check.sh
      TEXTFILE_DIR={{ cold_start_monitor_textfile_dir }}
      LOG_DIR={{ cold_start_monitor_log_dir }}
      CHECK_TIMEOUT_SECONDS={{ cold_start_monitor_timeout_seconds }}
      {{ cold_start_monitor_script_dir }}/cold-start-textfile-exporter.sh
      >/tmp/awoooi-cold-start-monitor.cron.log 2>&1
  tags: cold_start_monitor

- name: "cold-start monitor | 立即執行一次以刷新 textfile 指標"
  ansible.builtin.command:
    cmd: >-
      {{ cold_start_monitor_script_dir }}/cold-start-textfile-exporter.sh
  environment:
    CHECK_SCRIPT: "{{ cold_start_monitor_script_dir }}/full-stack-cold-start-check.sh"
    TEXTFILE_DIR: "{{ cold_start_monitor_textfile_dir }}"
    LOG_DIR: "{{ cold_start_monitor_log_dir }}"
    CHECK_TIMEOUT_SECONDS: "{{ cold_start_monitor_timeout_seconds | string }}"
  become: true
  become_user: "{{ cold_start_monitor_user }}"
  changed_when: false
  when: not ansible_check_mode
  tags: cold_start_monitor

- name: "cold-start monitor | 驗證 green metric 存在"
  ansible.builtin.command:
    cmd: >-
      grep -q 'awoooi_cold_start_last_result{host="110",scope="110_120_121_188",result="green"} 1'
      {{ cold_start_monitor_textfile_dir }}/cold_start_recovery.prom
  become: true
  become_user: "{{ cold_start_monitor_user }}"
  changed_when: false
  when: not ansible_check_mode
  tags: cold_start_monitor
