---
# AWOOOI Ansible — 192.168.0.188 AI+Web 中心完整狀態描述
# 執行: ansible-playbook -i inventory/hosts.yml playbooks/188-ai-web.yml
# CI: ansible-lint workflow uses the Gitea runner ubuntu-latest label.
#
# 預期狀態:
#   openclaw:       running (port 8088)
#   tsenyang:       running (port 3000)
#   momo:           running (port 5003)
#   signoz:         running (port 3301)
#   minio:          running (port 9000)
#   litellm:        optional/retired unless provider route is explicitly approved
#   n8n:            running (port 5678)
#   open-webui:     running (port 3010)
#   docker-registry: running (port 5001)
#   nginx:          all-sites.conf 無 gitlab block
#   keepalived:     MASTER priority 100 VIP:200

- name: "192.168.0.188 AI+Web 中心 — 預期狀態收斂"
  hosts: host_188
  become: true
  vars:
    ansible_become_pass: "{{ vault_sudo_password | default(omit) }}"

  roles:
    - role: host-textfile-exporters
      vars:
        host_textfile_user: ollama
        host_textfile_host_label: "188"
        host_textfile_manage_systemd_units: false
      tags: textfile_exporters

  tasks:
    # ========================================================================
    # Docker 服務健康檢查
    # ========================================================================
    - name: "Docker | 收集運作中的容器清單"
      ansible.builtin.command:
        cmd: "docker ps --format '{{ '{{' }}.Names{{ '}}' }}'"
      register: running_containers
      changed_when: false
      tags: docker

    - name: "Docker | 確認關鍵服務運作中"
      ansible.builtin.debug:
        msg: "⚠️  服務 {{ item }} 未在容器列表中，請確認"
      when: item not in running_containers.stdout
      loop:
        - openclaw
        - tsenyang
        - momo
        - signoz
        - minio
      tags: docker

    - name: "OpenClaw | 確認 systemd drop-in 目錄存在"
      ansible.builtin.file:
        path: /etc/systemd/system/clawbot.service.d
        state: directory
        owner: root
        group: root
        mode: "0755"
      tags:
        - docker
        - openclaw

    - name: "OpenClaw | 固定 systemd compose project 為 clawbot"
      ansible.builtin.copy:
        dest: /etc/systemd/system/clawbot.service.d/10-compose-project.conf
        owner: root
        group: root
        mode: "0644"
        content: |
          [Service]
          Environment=
          Environment=COMPOSE_PROJECT_NAME=clawbot
          RestartSec=30
      notify: Reload systemd
      tags:
        - docker
        - openclaw

    - name: "OpenClaw | 啟用 clawbot.service 並套用 daemon_reload"
      ansible.builtin.systemd:
        name: clawbot.service
        state: started
        enabled: true
        daemon_reload: true
      tags:
        - docker
        - openclaw

    # ========================================================================
    # 備份排程
    # ========================================================================
    - name: "Backup | 確認 momo backup 目錄存在"
      ansible.builtin.file:
        path: "{{ item }}"
        state: directory
        owner: ollama
        group: ollama
        mode: "0755"
      loop:
        - /home/ollama/bin
        - /home/ollama/momo_backups
      tags: backup_jobs

    - name: "Backup | 安裝 AwoooP ops 通知 helper"
      ansible.builtin.copy:
        src: "{{ playbook_dir }}/../../../scripts/ops/notify-awoooi-ops.sh"
        dest: /home/ollama/bin/notify-awoooi-ops.sh
        owner: ollama
        group: ollama
        mode: "0755"
      tags: backup_jobs

    - name: "Backup | 安裝 momo PostgreSQL 備份腳本"
      ansible.builtin.copy:
        src: "{{ playbook_dir }}/../../../scripts/backup/backup-momo-188-pg.sh"
        dest: /home/ollama/bin/momo-pg-backup.sh
        owner: ollama
        group: ollama
        mode: "0755"
      tags: backup_jobs

    - name: "Backup | 讀取既有 momo PostgreSQL crontab"
      ansible.builtin.command:
        cmd: "crontab -l -u ollama"
      register: momo_pg_crontab
      changed_when: false
      failed_when: momo_pg_crontab.rc not in [0, 1]
      tags: backup_jobs

    - name: "Backup | 移除未受 Ansible 管理的舊 momo PostgreSQL cron"
      ansible.builtin.shell: |
        set -euo pipefail
        legacy_path="{{ ['/home/ollama/momo-pro/scripts', 'pg_backup.sh'] | join('/') }}"
        crontab -l -u ollama 2>/dev/null \
          | awk -v p="$legacy_path" 'index($0, p) == 0' \
          | crontab -u ollama -
      args:
        executable: /bin/bash
      changed_when: true
      when: >-
        (['/home/ollama/momo-pro/scripts', 'pg_backup.sh'] | join('/'))
        in momo_pg_crontab.stdout
      tags: backup_jobs

    - name: "Backup | 安裝 momo PostgreSQL daily cron"
      ansible.builtin.cron:
        name: "AWOOOI momo PostgreSQL daily backup"
        user: ollama
        minute: "0"
        hour: "2"
        job: >-
          PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
          /home/ollama/bin/momo-pg-backup.sh
          >> /home/ollama/momo_backups/backup.log 2>&1
      tags: backup_jobs

    # ========================================================================
    # n8n / open-webui (Sprint A 新啟動)
    # ========================================================================
    - name: "N8N | 確認容器運作中"
      ansible.builtin.command:
        cmd: "docker ps --filter name=n8n --filter status=running --format '{{ '{{' }}.Names{{ '}}' }}'"
      register: n8n_status
      changed_when: false
      tags: n8n

    - name: "N8N | 若停止則啟動"
      ansible.builtin.command:
        cmd: "docker compose up -d"
        chdir: /opt/n8n
      changed_when: true
      when: n8n_status.stdout == ""
      tags: n8n

    - name: "Open-webui | 確認容器運作中"
      ansible.builtin.command:
        cmd: "docker ps --filter name=open-webui --filter status=running --format '{{ '{{' }}.Names{{ '}}' }}'"
      register: openwebui_status
      changed_when: false
      tags: open_webui

    - name: "Open-webui | 若停止則啟動"
      ansible.builtin.command:
        cmd: "docker compose up -d"
        chdir: /opt/open-webui
      changed_when: true
      when: openwebui_status.stdout == ""
      tags: open_webui

    # ========================================================================
    # Nginx 狀態確認
    # ========================================================================
    - name: "Nginx | 確認服務運作中"
      ansible.builtin.systemd:
        name: nginx
      register: nginx_status
      tags: nginx

    - name: "Nginx | 警告：nginx 未運作"
      ansible.builtin.debug:
        msg: "🚨 nginx 未運作！"
      when: nginx_status.status.ActiveState != "active"
      tags: nginx

    - name: "Nginx | 確認 all-sites.conf 無 gitlab block"
      ansible.builtin.command:
        cmd: "grep -c 'gitlab' /etc/nginx/sites-enabled/all-sites.conf"
      register: gitlab_check
      changed_when: false
      failed_when: false
      tags: nginx

    - name: "Nginx | 警告：all-sites.conf 仍含 gitlab block"
      ansible.builtin.debug:
        msg: "⚠️  all-sites.conf 仍含 gitlab 設定，請確認 Sprint A 清除是否完整"
      when: gitlab_check.stdout != "0"
      tags: nginx

    # ========================================================================
    # keepalived MASTER
    # ========================================================================
    - name: "Keepalived | 確認服務運作中"
      ansible.builtin.systemd:
        name: keepalived
      register: keepalived_status
      tags: keepalived

    - name: "Keepalived | 警告：keepalived 未運作"
      ansible.builtin.debug:
        msg: "⚠️  keepalived MASTER 未運作，VIP:200 降級為 110 BACKUP"
      when: keepalived_status.status.ActiveState != "active"
      tags: keepalived

    - name: "Keepalived | 確認 VIP:200 由本機持有"
      ansible.builtin.command:
        cmd: "ip addr show | grep 192.168.0.200"
      register: vip_check
      changed_when: false
      failed_when: false
      tags: keepalived

    - name: "Keepalived | 警告：VIP:200 不在本機"
      ansible.builtin.debug:
        msg: "⚠️  VIP 192.168.0.200 不在 188 (MASTER 可能已 failover 到 110)"
      when: vip_check.rc != 0
      tags: keepalived

  handlers:
    - name: Reload systemd
      ansible.builtin.systemd:
        daemon_reload: true
