---
# AWOOOI Ansible — 192.168.0.111 Ollama fallback proxy
# 原則: 111 的 Ollama 仍只綁本機，由 allowlist proxy 控制哪些主機能進入。

- name: "111 Ollama fallback allowlist 收斂"
  hosts: host_111
  gather_facts: false
  vars:
    proxy_label: com.momo.ollama111-allow-proxy
    proxy_user_uid: 501
    proxy_plist: /Users/ooo/Library/LaunchAgents/com.momo.ollama111-allow-proxy.plist
    allowed_cidrs: "127.0.0.1/32,192.168.0.111/32,192.168.0.188/32,192.168.0.110/32"

  tasks:
    - name: "Ollama111 | 讀取現行 allowlist"
      ansible.builtin.command:
        cmd: "/usr/libexec/PlistBuddy -c 'Print :EnvironmentVariables:OLLAMA111_PROXY_ALLOWED_CIDRS' {{ proxy_plist }}"
      register: current_allowlist
      changed_when: false
      tags: ["111", "ollama-fallback"]

    - name: "Ollama111 | 放行 110 proxy 進入 111 fallback"
      ansible.builtin.command:
        cmd: "/usr/libexec/PlistBuddy -c 'Set :EnvironmentVariables:OLLAMA111_PROXY_ALLOWED_CIDRS {{ allowed_cidrs }}' {{ proxy_plist }}"
      when: current_allowlist.stdout != allowed_cidrs
      changed_when: true
      notify: Restart ollama111 allow proxy
      tags: ["111", "ollama-fallback"]

    - name: "Ollama111 | 驗證本機 Ollama tag API"
      ansible.builtin.uri:
        url: http://127.0.0.1:11434/api/tags
        method: GET
        return_content: false
        status_code: 200
      changed_when: false
      tags: ["111", "ollama-fallback"]

  handlers:
    - name: Restart ollama111 allow proxy
      ansible.builtin.shell:
        cmd: |
          set -e
          launchctl enable gui/{{ proxy_user_uid }}/{{ proxy_label }} 2>/dev/null || true
          launchctl bootout gui/{{ proxy_user_uid }}/{{ proxy_label }} 2>/dev/null || true
          launchctl bootstrap gui/{{ proxy_user_uid }} {{ proxy_plist }}
      changed_when: true
