#!/usr/bin/env bash
# 188 Ollama 緊急封口。
# 不需要 root：把目前對外開放的 ollama serve 換成只綁 127.0.0.1:11434 的同使用者進程。
# 這是臨時手段；永久修法仍必須用 root 修改 systemd override。

set -euo pipefail

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

ssh -o BatchMode=yes -o ConnectTimeout=5 "$LEGACY_SSH" 'cat > ~/awoooi-ops/ollama-localhost-containment.sh <<'"'"'REMOTE_SH'"'"'
#!/usr/bin/env bash
set -euo pipefail

LOG="$HOME/awoooi-ops/ollama-localhost-containment.log"
SERVE_LOG="$HOME/awoooi-ops/ollama-localhost-serve.log"

{
  echo "=== containment start $(date) ==="
  echo "before:"
  ss -lntp | grep 11434 || true

  for i in $(seq 1 20); do
    pkill -u ollama -f "/usr/local/bin/ollama serve" 2>/dev/null || true
    sleep 0.2
    nohup env \
      PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin" \
      OLLAMA_HOST="127.0.0.1:11434" \
      OLLAMA_KEEP_ALIVE="30m" \
      OLLAMA_MAX_LOADED_MODELS="2" \
      OLLAMA_NUM_THREAD="14" \
      OLLAMA_NUM_PARALLEL="4" \
      OLLAMA_FLASH_ATTENTION="1" \
      OLLAMA_RUNNERS_DIR="/tmp/ollama_runners" \
      /usr/local/bin/ollama serve >> "$SERVE_LOG" 2>&1 &
    sleep 1
    if ss -lntp | grep -q "127.0.0.1:11434"; then
      echo "contained on attempt $i"
      break
    fi
  done

  echo "after:"
  ss -lntp | grep 11434 || true
  echo "local test:"
  curl -sS --max-time 3 http://127.0.0.1:11434/api/tags >/dev/null && echo LOCAL_OK || echo LOCAL_FAIL
  echo "=== containment end $(date) ==="
} | tee -a "$LOG"
REMOTE_SH
chmod +x ~/awoooi-ops/ollama-localhost-containment.sh
~/awoooi-ops/ollama-localhost-containment.sh'

echo "=== 驗證 LAN 入口 ==="
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 連線"
