---
# AWOOOI Ansible — Nginx 設定同步 Playbook
# 原則: Nginx conf 不再直接手改，所有修改透過此 Playbook 部署
# 執行: ansible-playbook -i inventory/hosts.yml playbooks/nginx-sync.yml --tags 188
# 乾跑: ansible-playbook -i inventory/hosts.yml playbooks/nginx-sync.yml --check

- name: "188 Nginx conf 同步"
  hosts: host_188
  become: true
  vars:
    ansible_become_pass: "{{ vault_sudo_password | default(omit) }}"
    nginx_conf_src: "{{ playbook_dir }}/../roles/nginx/templates/188-all-sites.conf.j2"
    nginx_conf_dest: /etc/nginx/sites-enabled/all-sites.conf

  tasks:
    - name: "nginx | 部署 all-sites.conf"
      ansible.builtin.template:
        src: "{{ nginx_conf_src }}"
        dest: "{{ nginx_conf_dest }}"
        owner: root
        group: root
        mode: "0644"
        backup: true
      notify: reload nginx
      tags: ["188", "nginx"]

    - name: "nginx | 測試設定"
      ansible.builtin.command:
        cmd: "nginx -t"
      changed_when: false
      tags: ["188", "nginx"]

  handlers:
    - name: reload nginx
      ansible.builtin.systemd:
        name: nginx
        state: reloaded

- name: "110 Ollama GCP Proxy 部署"
  hosts: host_110
  become: true
  vars:
    ansible_become_pass: "{{ vault_sudo_password | default(omit) }}"
    ollama_proxy_src: "{{ playbook_dir }}/../roles/nginx/templates/110-ollama-proxy.conf.j2"
    ollama_proxy_dest: /etc/nginx/sites-enabled/110-ollama-proxy.conf

  tasks:
    - name: "nginx | 確認 110 nginx 無 all-sites-from-188.conf 在 sites-enabled"
      ansible.builtin.stat:
        path: /etc/nginx/sites-enabled/all-sites-from-188.conf
      register: stale_conf
      tags: ["110", "nginx"]

    - name: "nginx | 警告：110 仍有 all-sites-from-188.conf (已非 188 管控)"
      ansible.builtin.debug:
        msg: "⚠️  110 sites-enabled 仍有 all-sites-from-188.conf，應已封存"
      when: stale_conf.stat.exists
      tags: ["110", "nginx"]

    # ADR-110: Ollama GCP 三層容災 — 110 作為 nginx proxy 轉發 K3s 流量到 GCP
    - name: "nginx | 部署 Ollama GCP Proxy 配置"
      ansible.builtin.template:
        src: "{{ ollama_proxy_src }}"
        dest: "{{ ollama_proxy_dest }}"
        owner: root
        group: root
        mode: "0644"
        backup: true
      notify: reload nginx 110
      tags: ["110", "nginx", "ollama-proxy"]

    - name: "nginx | 測試 110 設定"
      ansible.builtin.command:
        cmd: "nginx -t"
      changed_when: false
      tags: ["110", "nginx", "ollama-proxy"]

    - name: "nginx | 確認 nginx 已啟動"
      ansible.builtin.systemd:
        name: nginx
        state: started
        enabled: true
      tags: ["110", "nginx", "ollama-proxy"]

    - name: "nginx | 驗證 Ollama proxy 端口監聽"
      ansible.builtin.wait_for:
        port: "{{ item }}"
        host: 127.0.0.1
        timeout: 10
      loop:
        - 11435  # GCP-A
        - 11436  # GCP-B
        - 11437  # Local Fallback
      tags: ["110", "nginx", "ollama-proxy"]

  handlers:
    - name: reload nginx 110
      ansible.builtin.systemd:
        name: nginx
        state: reloaded
