#!/usr/bin/env bash
set -euo pipefail

# Install a user LaunchAgent that keeps the 111 Ollama LAN entrypoint behind
# scripts/ops/ollama111_allow_proxy.py. This avoids sudo/pfctl and keeps the
# real Ollama process bound to localhost while exposing an allowlisted LAN port.

PROJECT_DIR="${PROJECT_DIR:-$(cd "$(dirname "$0")/../.." && pwd)}"
LABEL="${OLLAMA111_PROXY_LABEL:-com.momo.ollama111-allow-proxy}"
PLIST_DIR="${HOME}/Library/LaunchAgents"
PLIST_PATH="${PLIST_DIR}/${LABEL}.plist"
LOG_DIR="${HOME}/Library/Logs"
PID_FILE="${HOME}/.ollama/ollama111-allow-proxy.pid"
INSTALL_DIR="${OLLAMA111_PROXY_INSTALL_DIR:-${HOME}/.local/share/momo-pro-system}"
INSTALL_SCRIPT_PATH="${INSTALL_DIR}/ollama111_allow_proxy.py"
PYTHON_BIN="${PYTHON_BIN:-/usr/bin/python3}"
OLLAMA_APP="${OLLAMA_APP:-/Applications/Ollama.app}"
OLLAMA_HOST_VALUE="${OLLAMA_HOST_VALUE:-127.0.0.1:11434}"
ALLOWED_CIDRS="${OLLAMA111_PROXY_ALLOWED_CIDRS:-127.0.0.1/32,192.168.0.111/32,192.168.0.188/32}"
GUI_DOMAIN="gui/$(id -u)"

if [[ ! -f "${PROJECT_DIR}/scripts/ops/ollama111_allow_proxy.py" ]]; then
  echo "missing proxy script under PROJECT_DIR=${PROJECT_DIR}" >&2
  exit 1
fi

mkdir -p "${PLIST_DIR}" "${LOG_DIR}" "${HOME}/.ollama" "${INSTALL_DIR}"
cp "${PROJECT_DIR}/scripts/ops/ollama111_allow_proxy.py" "${INSTALL_SCRIPT_PATH}"
chmod 0755 "${INSTALL_SCRIPT_PATH}"

launchctl setenv OLLAMA_HOST "${OLLAMA_HOST_VALUE}"

# Stop the ad-hoc nohup proxy from the initial incident response, if present.
if [[ -f "${PID_FILE}" ]]; then
  old_pid="$(cat "${PID_FILE}" 2>/dev/null || true)"
  if [[ -n "${old_pid}" ]]; then
    kill "${old_pid}" >/dev/null 2>&1 || true
  fi
  rm -f "${PID_FILE}"
fi
while IFS= read -r old_proxy_pid; do
  [[ -n "${old_proxy_pid}" ]] && kill "${old_proxy_pid}" >/dev/null 2>&1 || true
done < <(pgrep -f '[o]llama111_allow_proxy.py' || true)

# Restart Ollama so it observes the launchd user environment. The pgrep pattern
# intentionally avoids matching this installer command.
osascript -e 'quit app "Ollama"' >/dev/null 2>&1 || true
while IFS= read -r old_ollama_pid; do
  [[ -n "${old_ollama_pid}" ]] && kill "${old_ollama_pid}" >/dev/null 2>&1 || true
done < <(pgrep -f '[o]llama serve' || true)
sleep 2
open "${OLLAMA_APP}"

for _ in $(seq 1 20); do
  if curl -fsS --max-time 2 "http://${OLLAMA_HOST_VALUE}/api/version" >/dev/null 2>&1; then
    break
  fi
  sleep 1
done

cat > "${PLIST_PATH}" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${PYTHON_BIN}</string>
    <string>${INSTALL_SCRIPT_PATH}</string>
  </array>
  <key>WorkingDirectory</key>
  <string>${INSTALL_DIR}</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>OLLAMA111_PROXY_ALLOWED_CIDRS</key>
    <string>${ALLOWED_CIDRS}</string>
    <key>OLLAMA111_PROXY_LISTEN_HOST</key>
    <string>192.168.0.111</string>
    <key>OLLAMA111_PROXY_LISTEN_PORT</key>
    <string>11434</string>
    <key>OLLAMA111_PROXY_TARGET_HOST</key>
    <string>127.0.0.1</string>
    <key>OLLAMA111_PROXY_TARGET_PORT</key>
    <string>11434</string>
    <key>PYTHONUNBUFFERED</key>
    <string>1</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${LOG_DIR}/ollama111-allow-proxy.log</string>
  <key>StandardErrorPath</key>
  <string>${LOG_DIR}/ollama111-allow-proxy.err.log</string>
</dict>
</plist>
PLIST

launchctl bootout "${GUI_DOMAIN}" "${PLIST_PATH}" >/dev/null 2>&1 || true
: > "${LOG_DIR}/ollama111-allow-proxy.err.log"
launchctl bootstrap "${GUI_DOMAIN}" "${PLIST_PATH}"
launchctl kickstart -k "${GUI_DOMAIN}/${LABEL}"

sleep 2
echo "installed ${LABEL}"
echo "plist=${PLIST_PATH}"
echo "script=${INSTALL_SCRIPT_PATH}"
echo "allowed=${ALLOWED_CIDRS}"
launchctl print "${GUI_DOMAIN}/${LABEL}" | head -40 || true
tail -20 "${LOG_DIR}/ollama111-allow-proxy.log" || true
