#!/bin/bash
PKG="com.hottagames.yh.laohu"
INJECT="inject"
LIB="libProject.so"

# ========== 颜色定义 ==========
RED='\033[1;31m'
GREEN='\033[1;32m'
BLUE='\033[1;36m'
YELLOW='\033[1;33m'
NC='\033[0m'

# ========== 启动公益提示（显示3秒） ==========
clear
echo -e "\n\n"
echo -e "${BLUE}=============================================${NC}"
echo -e "${YELLOW}  本辅助为公益 如果你是花钱买来的${NC}"
echo -e "${YELLOW}        就说明你被圈了${NC}"
echo -e "${GREEN}          ZMC官方频道@XYSY0${NC}"
echo -e "${BLUE}=============================================${NC}"
echo -e "\n\n"
sleep 3
clear

# ========== 打印函数 ==========
function print_info() {
    echo -e "${GREEN}[+]${NC} $1"
}
function print_error() {
    echo -e "${RED}[-]${NC} $1"
}

# ========== 检查ROOT ==========
if [ $(id -u) != 0 ]; then
    print_error "请使用 root 权限运行"
    exit 1
fi

# ========== 1. 等待游戏进程启动 ==========
print_info "等待游戏进程 $PKG 启动..."
while true; do
    PID=$(pidof "$PKG" 2>/dev/null)
    if [ -n "$PID" ]; then
        print_info "游戏进程已启动，PID=$PID"
        break
    fi
    sleep 1
done

# ========== 2. 等待 libUnreal.so 加载 ==========
print_info "等待 libUnreal.so 加载..."
MAX_WAIT=30
WAIT_COUNT=0
while [ $WAIT_COUNT -lt $MAX_WAIT ]; do
    if grep -q "libUnreal.so" /proc/$PID/maps 2>/dev/null; then
        print_info "libUnreal.so 已加载"
        break
    fi
    sleep 1
    WAIT_COUNT=$((WAIT_COUNT + 1))
done
if [ $WAIT_COUNT -ge $MAX_WAIT ]; then
    print_error "超时未检测到 libUnreal.so，请确认游戏是否正常运行"
    exit 1
fi
sleep 3

# ========== 3. 部署并注入 ==========
print_info "部署文件..."
cp -f "$LIB" "/data/data/$PKG/"
chmod 755 "/data/data/$PKG/$LIB"
cp -f "$INJECT" "/data/data/$PKG/"
chmod 777 "/data/data/$PKG/$INJECT"

if [ -f "/data/data/$PKG/$LIB" ] && [ "$(stat -c '%a' "/data/data/$PKG/$LIB")" = "755" ]; then
    print_info "动态库文件就绪"
else
    print_error "动态库文件部署失败"
    exit 1
fi

if [ -f "/data/data/$PKG/$INJECT" ] && [ "$(stat -c '%a' "/data/data/$PKG/$INJECT")" = "777" ]; then
    print_info "注入工具就绪"
else
    print_error "注入工具部署失败"
    exit 1
fi

print_info "开始注入..."
/system/bin/su -c "/data/data/$PKG/$INJECT -f $PKG -n $PKG -so /data/data/$PKG/$LIB"

# 清理
rm -f "/data/data/$PKG/$INJECT"
rm -f "/data/data/$PKG/$LIB"

echo -e "\n${GREEN}=================================${NC}"
print_info "注入完成，感谢使用ZMC"
echo -e "${GREEN}=================================${NC}\n"
