#! /vendor/bin/sh

update_build_prop() {
    local FILE=$1
    local STR=$2
    local VALUE=$3

    if [ `grep -c "$STR" $FILE` -ne '0' ]; then
        sed -i "s/$STR.*/$STR$VALUE/" $FILE
    else
        echo "$STR$VALUE" >> $FILE
    fi
}

target_file="newlink_update.sh"
media_root="/mnt/media_rw"
found=0
usb_name="sda1"

# 遍历所有U盘挂载点（仅检查根目录）
for usb_mount in "$media_root"/*; do
    # 跳过非目录和空匹配
    [ -d "$usb_mount" ] || continue
    [ -e "$usb_mount" ] || break

    # 直接检查根目录下的文件是否存在（不递归子目录）
    if [ -f "$usb_mount/$target_file" ]; then
        usb_name=$(basename "$usb_mount")
        echo "SUCCESS: File '$target_file' found in USB root: $usb_name"
        break
    fi
done

if [ -f /data/local/nl_build_true2 ];
then
    sleep 5
    path="/mnt/media_rw/$usb_name/NL_CUS.txt"
    echo "该机器已经配置过" > "$path"
    am start -n com.newlink.service/.activity.USBActivity --es "path" "$path"
    sleep 5
    rm -rf /mnt/media_rw/$usb_name/NL_CUS.txt
else
	mount -o rw,remount /
	rm -rf /system/app/*Launcher*
	rm -rf /system/app/*launcher*
	cp -r /mnt/media_rw/$usb_name/Boot/ /system/app/
	cp -r /mnt/media_rw/$usb_name/OpenDesktop/ /system/app/
	cp -r /mnt/media_rw/$usb_name/POVODOTool/ /system/app/
	chmod 755 -R /system/app/Boot/
	chmod 755 -R /system/app/OpenDesktop/
	chmod 755 -R /system/app/POVODOTool/
	sync
	path="/mnt/media_rw/$usb_name/NL_CUS.txt"
	echo "配置成功，五秒后重启" > "$path"
	am start -n com.newlink.service/.activity.USBActivity --es "path" "$path"
	sleep 5
	rm -rf /mnt/media_rw/$usb_name/NL_CUS.txt
	touch /data/local/nl_build_true2
	echo auto_wakeup 1 > /proc/msp/pm
	sleep 1
	setprop sys.powerctl shutdown
fi