#!/system/bin/sh

RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
CYAN='\033[1;36m'
NC='\033[0m'

CUR_DIR=$(pwd)
MODULE_DIR="$CUR_DIR/ko_data"
SAVE_PATH="/data/adb/chen/v1/qudong.txt"
ORIG_STR="usa_drv_orig"

if [ -f "$SAVE_PATH" ]; then
    LAST_NAME=$(cat "$SAVE_PATH")
    if [ ! -z "$LAST_NAME" ] && lsmod | grep -qw "$LAST_NAME"; then
        echo -e "${YELLOW}[!] 发现存留驱动: ${PURPLE}$LAST_NAME${NC}"
        echo -n -e "${YELLOW}[?] 是否执行 rmmod 卸载？(y/n): ${NC}"
        read confirm
        if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
            rmmod_msg=$(rmmod "$LAST_NAME" 2>&1)
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}[+] 卸载成功${NC}"
            else
                echo -e "${RED}[-] 卸载失败: $rmmod_msg${NC}"
                exit 1
            fi
        fi
    fi
fi

echo -e "\n${BLUE}--- 请选择驱动文件 (输入 q 退出) ---${NC}"
i=1
unset files
for file in "$MODULE_DIR"/*.ko; do
    if [ -f "$file" ]; then
        files[$i]="$file"
        echo -e "  ${GREEN}$i)${NC} $(basename "$file")"
        i=$((i+1))
    fi
done

if [ $i -eq 1 ]; then
    echo -e "${RED}[!] 错误: $MODULE_DIR 内无驱动文件${NC}"
    exit 1
fi

echo -e "${BLUE}--------------------------------------${NC}"
echo -n -e "${CYAN}输入编号: ${NC}"
read choice

if [ "$choice" = "q" ] || [ "$choice" = "Q" ]; then
    echo -e "${YELLOW}已取消操作，退出。${NC}"
    exit 0
fi

SELECTED_KO="${files[$choice]}"
if [ -z "$SELECTED_KO" ]; then
    echo -e "${RED}[!] 选择无效${NC}"
    exit 1
fi

RANDOM_STR=$(tr -dc 'a-zA-Z' < /dev/urandom | head -c 12)
TEMP_KO_NAME="temp_${RANDOM_STR}.ko"
TEMP_KO_PATH="$CUR_DIR/$TEMP_KO_NAME"

sed "s/$ORIG_STR/$RANDOM_STR/g" "$SELECTED_KO" > "$TEMP_KO_PATH"
chmod 644 "$TEMP_KO_PATH"

mkdir -p "$(dirname "$SAVE_PATH")" 2>/dev/null
load_error=$(insmod "$TEMP_KO_PATH" 2>&1)

if [ $? -eq 0 ]; then
    echo -e "${GREEN}>>> [成功] 驱动已挂载: ${PURPLE}$RANDOM_STR${NC}"
    echo "$RANDOM_STR" > "$SAVE_PATH"
else
    echo -e "${RED}>>> [失败] 原因: $load_error${NC}"
    dmesg | grep $RANDOM_STR
fi

[ -f "$TEMP_KO_PATH" ] && rm -f "$TEMP_KO_PATH"
