#!/bin/bash
VSCODE_PATCH_DIR="$HOME/.vscode-patch"
VSCODE_APP_PATH=""

echo "[VSCode 应用程序补丁工具]"

# 1. 检查补丁工具文件夹
if [ ! -d "$VSCODE_PATCH_DIR/lib" ]; then
  echo "错误：补丁文件夹应放在这儿：$HOME/.vscode-patch/"
  echo "请先运行以下命令安装补丁工具："
  echo "git clone --depth 1 https://git.unvec.site/stevenhobs/vscode-patch ~/.vscode-patch"
  echo "chmod -R +751 ~/.vscode-patch"
  exit 1
fi

# 2. 获取VSCode安装路径
if [ -n "$1" ]; then
  if [[ "$1" != /* ]]; then
    VSCODE_APP_PATH="$(realpath "$1")"
  else
    VSCODE_APP_PATH="$1"
  fi
else
  read -p "指定VSCode App路径: " VSCODE_APP_PATH
fi

echo "-- VSCode安装路径：$VSCODE_APP_PATH"

# 3. 验证路径有效性
if [ ! -f "$VSCODE_APP_PATH/code" ]; then
  echo "错误：指定路径下不存在VSCode可执行文件"
  exit 1
fi

echo "-- 找到VSCode可执行文件：$VSCODE_APP_PATH/code"

# 4. 检查是否已补丁过
if strings "$VSCODE_APP_PATH/code" | grep -q "$VSCODE_PATCH_DIR/lib" 2>/dev/null; then
  echo "-- 程序已被补丁过，无需重复操作"
  exit 0
fi

# 5. 备份原始文件
BACKUP_FILE="$VSCODE_APP_PATH/code.bak"
if [ ! -f "$BACKUP_FILE" ]; then
  echo "-- 备份原始程序..."
  cp "$VSCODE_APP_PATH/code" "$BACKUP_FILE"
  if [ $? -ne 0 ]; then
    echo "-- 错误：备份失败"
    exit 1
  fi
else
  echo "-- 已存在备份文件：$BACKUP_FILE"
fi

# 6. 执行补丁
echo "-- 开始补丁..."
"$VSCODE_PATCH_DIR/tools/patchelf" \
  --set-interpreter "$VSCODE_PATCH_DIR/lib/ld-linux-x86-64.so.2" \
  --set-rpath "\$ORIGIN:$HOME/.vscode-patch/lib" \
  "$VSCODE_APP_PATH/code"

# 7. 检查补丁结果
if [ $? -eq 0 ]; then
  echo "-- 补丁成功！"
  
  # 创建补丁说明文件
  PATCH_INFO_FILE="$VSCODE_APP_PATH/Patch说明.md"
  echo "VSCode App 已做旧版本兼容动态库补丁" > "$PATCH_INFO_FILE"
  echo "补丁时间：$(date)" >> "$PATCH_INFO_FILE"
  echo "原始文件备份：code.bak" >> "$PATCH_INFO_FILE"
  echo "补丁数据路径：$VSCODE_PATCH_DIR" >> "$PATCH_INFO_FILE"
  echo "补丁操作：修改动态链接器和库路径" >> "$PATCH_INFO_FILE"
else
  echo "-- 错误：补丁失败，恢复原始文件"
  if [ -f "$BACKUP_FILE" ]; then
    cp "$BACKUP_FILE" "$VSCODE_APP_PATH/code"
    echo "-- 已恢复原始程序"
  fi
  exit 1
fi
