#!/bin/bash
# 闲仓自助攒机 - MAC版启动器
# 通过终端间接启动，绕开 app bundle 的沙箱限制

APP_ROOT="$(cd "$(dirname "$0")/../Resources/app" && pwd)"

# 写一个临时启动脚本
LAUNCHER="$APP_ROOT/.run-server.command"
cat > "$LAUNCHER" << 'ENDSCRIPT'
#!/bin/bash
APP_ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$APP_ROOT"

export XIANCHANG_SYNC_DATA_DIR="/tmp/xianchang-sync-data"
PORT=8898
WATCHDOG_PORT=8899
URL="http://localhost:${PORT}/?v=181&_t=$(date +%s)"

# 寻找可用的 python3
find_python() {
  for py in \
    "$HOME/.pyenv/shims/python3" \
    "/usr/local/bin/python3" \
    "/opt/homebrew/bin/python3" \
    "/Library/Frameworks/Python.framework/Versions/Current/bin/python3" \
    "$(command -v python3 2>/dev/null)" \
    "/usr/bin/python3"; do
    if [ -x "$py" ]; then
      if "$py" -c "print('ok')" >/dev/null 2>&1; then
        echo "$py"
        return 0
      fi
    fi
  done
  return 1
}

PYTHON_BIN="$(find_python)"

if [ -z "$PYTHON_BIN" ]; then
  osascript -e 'display dialog "未找到可用的 Python 3，请先安装 Python 3。'$'\n''安装方法：打开终端执行 brew install python3" buttons {"知道了"} default button 1'
  exit 1
fi

# 启动看门狗（完全后台，脱离终端）
nohup "$PYTHON_BIN" "$APP_ROOT/watchdog.py" > /tmp/xianchang-watchdog.log 2>&1 &
disown
sleep 0.3

# 杀旧服务
OLD_PIDS=$(lsof -tiTCP:${PORT} -sTCP:LISTEN 2>/dev/null || true)
if [ -n "$OLD_PIDS" ]; then
  kill $OLD_PIDS 2>/dev/null || true
  sleep 0.3
fi

# 启动主服务（完全后台，脱离终端）
nohup "$PYTHON_BIN" "$APP_ROOT/sync-server.py" --host 0.0.0.0 --port "$PORT" --no-open-browser > /tmp/xianchang-server.log 2>&1 &
disown

# 等待服务就绪
READY=0
for i in $(seq 1 33); do
  if curl -s --max-time 0.3 "http://localhost:${PORT}/" >/dev/null 2>&1; then
    READY=1
    break
  fi
  sleep 0.15
done

# 打开浏览器
if [ -d "/Applications/QQBrowser.app" ]; then
  open -a "QQBrowser" "$URL"
  # 等待浏览器打开后，设置窗口始终置顶并进入全屏
  (
    sleep 2.5
    osascript << 'EOF' 2>/dev/null
tell application "QQBrowser"
  activate
  try
    tell front window
      set miniaturizable to false
      set closeable to false
    end tell
  end try
end tell
EOF
  ) &
else
  open "$URL"
fi

# 延迟关闭终端窗口，如果没有其他窗口就退出终端应用
nohup osascript -e 'delay 1' -e 'tell application "Terminal"' -e 'try' -e 'close (every window whose name contains ".run-server.command") saving no' -e 'end try' -e 'delay 0.5' -e 'if (count of windows) = 0 then quit' -e 'end tell' >/dev/null 2>&1 &

exit 0
ENDSCRIPT

chmod +x "$LAUNCHER"

# 用终端打开启动脚本
osascript -e "tell application \"Terminal\" to do script \"'$LAUNCHER'\"" > /dev/null 2>&1

# 如果上面失败了，直接用 open 命令
if [ $? -ne 0 ]; then
  open "$LAUNCHER"
fi

exit 0
