#!/bin/sh
# 将系统模板同步到当前用户的 ~/.kylinbot-pyenv
set -e

TEMPLATE="${KYLINBOT_PYTHON_TEMPLATE:-/opt/kylin-bot/python/template}"
DEST="${KYLINBOT_PYENV:-$HOME/.kylinbot-pyenv}"
MODE="ask"

case "${1:-}" in
  --force|--yes|-y|-f) MODE="force" ;;
  --force-clean|--clean) MODE="force-clean" ;;
  -h|--help)
    echo "用法: kylinbot-pyenv-clone [--force|--force-clean]"
    exit 0
    ;;
esac

if [ ! -x "$TEMPLATE/bin/python" ] && [ ! -x "$TEMPLATE/bin/python3" ]; then
  echo "ERROR: 系统模板不存在或不可用: $TEMPLATE" >&2
  exit 1
fi

ask_overwrite() {
  if [ ! -t 0 ] && [ ! -t 1 ]; then
    echo "已存在用户环境且当前为非交互终端，跳过: $DEST" >&2
    echo "覆盖更新请加: kylinbot-pyenv-clone --force" >&2
    return 1
  fi
  printf "已存在用户环境: %s\n确认覆盖更新? [y/N]: " "$DEST"
  if [ -r /dev/tty ]; then read -r ans </dev/tty || ans=""; else read -r ans || ans=""; fi
  case "$ans" in y|Y|yes|YES|Yes) return 0 ;; *) return 1 ;; esac
}

# Prefer real interpreter for shebang rewrite so pip/tools do not use the
# python3 routing shim as sys.executable. Public PATH name remains bin/python3
# (shim) from the template.
resolve_real_python() {
  if [ -x "$DEST/bin/python3.12" ]; then
    echo "$DEST/bin/python3.12"
    return 0
  fi
  if [ -x "$DEST/bin/python3" ]; then
    # Skip routing shim (starts with shebang); prefer a real binary named python3.
    case "$(head -c 2 "$DEST/bin/python3" 2>/dev/null || true)" in
      '#!') ;;
      *)
        echo "$DEST/bin/python3"
        return 0
        ;;
    esac
  fi
  if [ -x "$DEST/bin/python" ]; then
    echo "$DEST/bin/python"
    return 0
  fi
  # Last resort: public python3 (may be shim; still runnable)
  echo "$DEST/bin/python3"
}

fix_user_paths() {
  PY="$(resolve_real_python)"
  if [ -d "$DEST/bin" ]; then
    for f in "$DEST/bin"/*; do
      [ -f "$f" ] || continue
      base=$(basename "$f")
      # Never rewrite the public python3 shim or the real interpreter binary.
      case "$base" in
        python3|python3.12|python|kylinbot-python3-system-routes.list) continue ;;
      esac
      if head -c 2 "$f" 2>/dev/null | grep -q '#!'; then
        if head -n 1 "$f" | grep -Eq 'python'; then
          sed -i "1s|^#!.*|#!$PY|" "$f" || true
        fi
      fi
    done
  fi
  if [ -f "$TEMPLATE/.kylinbot-python-version" ]; then
    cp -f "$TEMPLATE/.kylinbot-python-version" "$DEST/.kylinbot-python-version"
    echo "cloned_from=$TEMPLATE" >> "$DEST/.kylinbot-python-version"
    echo "cloned_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$DEST/.kylinbot-python-version"
  fi
}

overlay_from_template() {
  mkdir -p "$DEST"
  if command -v rsync >/dev/null 2>&1; then
    rsync -a --exclude='__pycache__/' --exclude='*.pyc' --exclude='*.pyo' "$TEMPLATE/" "$DEST/"
  else
    (cd "$TEMPLATE" && tar cf - .) | (cd "$DEST" && tar xpf -)
  fi
  fix_user_paths
}

fresh_clone() {
  mkdir -p "$(dirname "$DEST")"
  if command -v rsync >/dev/null 2>&1; then
    mkdir -p "$DEST"
    rsync -a --delete --exclude='__pycache__/' --exclude='*.pyc' --exclude='*.pyo' "$TEMPLATE/" "$DEST/"
  else
    rm -rf "$DEST"
    cp -a "$TEMPLATE" "$DEST"
  fi
  fix_user_paths
}

if [ ! -e "$DEST" ]; then
  fresh_clone
else
  case "$MODE" in
    force) overlay_from_template ;;
    force-clean)
      mv "$DEST" "$DEST.bak.$(date +%Y%m%d%H%M%S)"
      fresh_clone
      ;;
    ask)
      if ask_overwrite; then overlay_from_template; else exit 0; fi
      ;;
  esac
fi

echo "验证: $DEST/bin/python3 --version"
"$DEST/bin/python3" --version
