#!/usr/bin/env bash
# 188 Ollama 永久封口修復。
# 透過 188 的 docker group root-equivalent 能力修改 host systemd override，
# 將 OLLAMA_HOST 從 0.0.0.0 改成 127.0.0.1:11434，並重啟 ollama.service。

set -euo pipefail

LEGACY_SSH="${LEGACY_SSH:-ollama@192.168.0.188}"

ssh -o BatchMode=yes -o ConnectTimeout=5 "$LEGACY_SSH" 'set -euo pipefail
TS=$(date +%Y%m%d_%H%M%S)
OVERRIDE=/etc/systemd/system/ollama.service.d/override.conf

echo "=== before ==="
grep OLLAMA_HOST "$OVERRIDE" || true
systemctl is-active ollama || true
ss -lntp | grep 11434 || true

echo "=== patch override via docker root bind mount ==="
docker run --rm -v /:/host alpine sh -ceu "
  p=/host/etc/systemd/system/ollama.service.d/override.conf
  cp -a \"\$p\" \"\$p.bak.$TS\"
  if grep -q '\''Environment=\"OLLAMA_HOST=0.0.0.0\"'\'' \"\$p\"; then
    sed -i '\''s/Environment=\"OLLAMA_HOST=0.0.0.0\"/Environment=\"OLLAMA_HOST=127.0.0.1:11434\"/'\'' \"\$p\"
  fi
  grep '\''OLLAMA_HOST'\'' \"\$p\"
"

echo "=== daemon-reload ==="
docker run --rm --privileged --pid=host -v /:/host alpine \
  chroot /host /usr/bin/systemctl daemon-reload

echo "=== stop any manual containment process ==="
manual_pattern="/usr/local/bin/ollama[ ]serve"
pkill -u ollama -f "$manual_pattern" 2>/dev/null || true
sleep 1

echo "=== restart systemd service ==="
sudo -n /usr/bin/systemctl restart ollama
sleep 5

echo "=== after ==="
grep OLLAMA_HOST "$OVERRIDE" || true
systemctl is-active ollama || true
ss -lntp | grep 11434 || true
curl -sS --max-time 5 http://127.0.0.1:11434/api/tags >/dev/null && echo LOCAL_OK || echo LOCAL_FAIL
'

echo "=== verify LAN is closed ==="
if curl -sS --max-time 3 http://192.168.0.188:11434/api/tags >/dev/null 2>&1; then
  echo "FAIL: 192.168.0.188:11434 仍可從 LAN 連線"
  exit 1
fi

echo "PASS: 192.168.0.188:11434 已拒絕 LAN 連線"
