#!/bin/sh
# 汇理极知 / RatioMax Harness — Linux launcher.
#
# Starts the bundled DeepSeek Harness runtime with the `ratiomax` profile and
# lets dsh open the default browser on the tokenised URL. The DSH home is kept
# under the user's data directory so sessions and settings survive upgrades.
set -eu

SELF="$(readlink -f "$0")"
APP_DIR="$(cd "$(dirname "$SELF")/.." && pwd)"
DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}/ratiomax-harness"
DSH_HOME="$DATA_HOME/dsh-home"
PORT="${RATIOMAX_PORT:-3097}"

# Seed the per-user DSH home on first launch (profile, splash/wallpaper config,
# credentials). Later launches keep whatever the user changed.
if [ ! -f "$DSH_HOME/profiles/ratiomax/package.json" ]; then
  mkdir -p "$DSH_HOME"
  # 包内是空的凭证骨架（不含密钥），逐项复制，单文件失败不阻断启动。
  cp -a "$APP_DIR/seed/." "$DSH_HOME/" 2>/dev/null || true
fi
chmod 600 "$DSH_HOME/.credentials.yaml" 2>/dev/null || true

# Package upgrades ship a newer bundle inside the package; refresh just the
# bundle copies (never the profile patch or user settings) when the seed is newer.
# Managed configuration: disable the official DeepSeek session-log uploader and
# the model/provider settings page (the product configures models server-side).
PATCH_FILE="$DSH_HOME/profiles/ratiomax/cordis.patch.yml"
if [ -f "$PATCH_FILE" ] && ! grep -q "ratiomax-managed" "$PATCH_FILE" 2>/dev/null; then
  cat >> "$PATCH_FILE" <<'RATIOMAX_MANAGED'

# ratiomax-managed: 会话日志只上传到汇理极知服务器；模型与供应商由服务器配置。
- id: session-log-deepseek
  disabled: true
- id: ui-settings-session-log
  disabled: true
- id: ui-settings-models
  disabled: true
RATIOMAX_MANAGED
fi

SEED_VERSION="$(cat "$APP_DIR/seed/VERSION" 2>/dev/null || true)"
SEED_MARKER="$DSH_HOME/.seed-version"
INSTALLED_VERSION="$(cat "$SEED_MARKER" 2>/dev/null || true)"
if [ -n "$SEED_VERSION" ] && [ "$SEED_VERSION" != "$INSTALLED_VERSION" ]; then
  for bundle in "@ratiomax/dsh-harness" "dsh-boot-suite"; do
    src="$APP_DIR/seed/profiles/ratiomax/node_modules/$bundle"
    dst="$DSH_HOME/profiles/ratiomax/node_modules/$bundle"
    if [ -d "$src" ]; then
      rm -rf "$dst"
      mkdir -p "$(dirname "$dst")"
      cp -a "$src" "$dst"
    fi
  done
  for file in client.json product.json; do
    if [ ! -f "$DSH_HOME/$file" ] && [ -f "$APP_DIR/seed/$file" ]; then
      cp -a "$APP_DIR/seed/$file" "$DSH_HOME/$file" 2>/dev/null || true
    fi
  done
  echo "$SEED_VERSION" > "$SEED_MARKER"
fi

# Self-check: proves the package carries its own Node + dsh, no host install needed.
if [ "${1:-}" = "--selftest" ]; then
  echo "包目录:      $APP_DIR"
  echo "自带 node:   $("$APP_DIR/runtime/node" --version)"
  echo "自带 dsh:    $("$APP_DIR/runtime/node" "$APP_DIR/runtime/lib/bin.js" --version 2>&1 | head -1)"
  echo "用户数据:    $DSH_HOME"
  if DSH_HOME="$DSH_HOME" "$APP_DIR/runtime/node" "$APP_DIR/runtime/lib/bin.js" \
       --profile ratiomax --dump-config >/dev/null 2>&1; then
    echo "profile:     OK (ratiomax)"
  else
    echo "profile:     FAILED"
  fi
  exit 0
fi

# 不再从 $HOME/.dsh 复制凭证：新装用户用自己的手机号登录，模型令牌由服务器下发。

# A previous session may have downloaded a full package update and asked the app
# to restart. Install it now, before starting the new version.
FULL_MARKER="$DSH_HOME/update/apply-full.json"
if [ -f "$FULL_MARKER" ]; then
  INSTALLER="$(sed -n 's/.*"installer"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$FULL_MARKER" | head -1)"
  if [ -n "$INSTALLER" ] && [ -f "$INSTALLER" ]; then
    echo "安装已下载的完整更新：$INSTALLER"
    if command -v pkexec >/dev/null 2>&1 && [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
      pkexec dpkg -i "$INSTALLER" || echo "更新安装未完成，请手动执行：sudo dpkg -i \"$INSTALLER\""
    else
      sudo -n dpkg -i "$INSTALLER" 2>/dev/null || echo "需要管理员权限安装：sudo dpkg -i \"$INSTALLER\""
    fi
  fi
  rm -f "$FULL_MARKER"
fi

export DSH_HOME
export RATIOMAX_HARNESS_APP="$APP_DIR"
export RATIOMAX_APP_ROOT="$APP_DIR"
# Keep the bundled runtime first so a system-wide dsh install cannot win.
export PATH="$APP_DIR/runtime:$PATH"

mkdir -p "$DSH_HOME/logs"
LOG="$DSH_HOME/logs/harness-$(date +%Y%m%d).log"

# Desktop client only: Electron starts the bundled harness on 127.0.0.1 with a
# random port and token, so no browser URL is ever exposed to the user.
ELECTRON="$APP_DIR/client/electron"
APP_ENTRY="$APP_DIR/client/resources/app"
if [ ! -x "$ELECTRON" ] || [ ! -d "$APP_ENTRY" ]; then
  echo "客户端文件缺失：$ELECTRON / $APP_ENTRY" >&2
  exit 1
fi
exec "$ELECTRON" "$APP_ENTRY" "$@" >>"$LOG" 2>&1
