#!/bin/bash
# save as strip_other_funcs.sh

# 输入参数检查
if [ $# -ne 1 ]; then
    echo "Usage: $0 <binary_file>"
    exit 1
fi

TARGET_BIN="$1"
BACKUP_BIN="${TARGET_BIN}.bak"

# 定义要保留的函数列表
TARGET_FUNCTIONS=(
    "Lenheart()"
    "_Inter_LoadGeolocation_dispatch_sig(void*, void*, char*)"
    "SocketThread_function(void*)"
    "PrintAuroraTag()"
    "InitSquirrel()"
    "ReloadingScript(SQVM*, std::string)"
    "ReqSquirrelScript(SQVM*)"
    "Cutecode(char*, int*, int, int)"
)

# 创建备份
cp "$TARGET_BIN" "$BACKUP_BIN"

# 获取保留符号列表
KEEP_SYMBOLS=()
while read -r symbol; do
    demangled=$(c++filt "$symbol" 2>/dev/null)
    for target in "${TARGET_FUNCTIONS[@]}"; do
        if [[ "$demangled" == "$target" ]]; then
            KEEP_SYMBOLS+=("$symbol")
            break
        fi
    done
done < <(nm --defined-only "$BACKUP_BIN" | awk '/ [TtWw] /{print $3}')

if [ ${#KEEP_SYMBOLS[@]} -eq 0 ]; then
    echo "Error: No target symbols found!"
    exit 2
fi

# 生成保留符号文件
KEEP_FILE=$(mktemp)
printf "%s\n" "${KEEP_SYMBOLS[@]}" > "$KEEP_FILE"

# 执行符号清理
echo "Stripping symbols..."
objcopy --strip-all \
    --keep-symbols="$KEEP_FILE" \
    "$BACKUP_BIN" \
    "$TARGET_BIN"

# 清理临时文件
rm -f "$KEEP_FILE"

echo "Done. Original backup at: $BACKUP_BIN"
