@echo off
setlocal enabledelayedexpansion

REM Delete previous log files
del unreachable.txt 2>nul
del failure.txt 2>nul
del success.txt 2>nul
echo Initializing
netsh interface show interface >nul 2>&1



REM Check if an argument is provided or if iplist.txt exists
if "%~1"=="" (
    if not exist iplist.txt (
        echo Error: No IP address provided and iplist.txt does not exist.
        echo Please provide an IP address as an argument or create iplist.txt.
        EXIT /B 1
    )
) else (
    REM Argument provided, use it as the IP
    set "ip=%~1"
)

REM Check if commands.txt exists
if not exist commands.txt (
    echo Error: commands.txt not found. Please create commands.txt with the commands to execute.
    EXIT /B 1
)

REM If no argument provided, process IPs from iplist.txt
if "%~1"=="" (
    for /f "tokens=*" %%s in (iplist.txt) do (
        call :process_ip %%s
    )
) else (
    REM Process the provided IP
    call :process_ip %ip%
)

GOTO :EOF

:process_ip
set "ip=%~1"
echo PINGING %ip%

REM Ping the IP and check if it's reachable
ping -n 1 -w 1000 %ip% >nul 2>&1

if %ERRORLEVEL% EQU 0 (
    echo %ip% is reachable
    call :MAIN %ip%
) else (
    echo %ip% >> unreachable.txt
    echo %ip% is unreachable. Skipping...
)
EXIT /B 0

:MAIN
set "ip=%1"
echo CONNECTING to %ip%
adb disconnect > nul 2>&1

set "success=1"

REM Execute the pre-defined adb commands
call :run_command "adb connect %ip%"
IF %ERRORLEVEL% NEQ 0 set "success=0" & goto :end_main
timeout /t 2 /nobreak > nul

call :run_command "adb root"
IF %ERRORLEVEL% NEQ 0 set "success=0" & goto :end_main
timeout /t 2 /nobreak > nul

call :run_command "adb connect %ip%"
IF %ERRORLEVEL% NEQ 0 set "success=0" & goto :end_main
timeout /t 2 /nobreak > nul

call :run_command "adb remount"
IF %ERRORLEVEL% NEQ 0 set "success=0" & goto :end_main
timeout /t 2 /nobreak > nul

adb shell "getprop ro.boot.mac | tr -d ':' | tr '[:lower:]' '[:upper:]'"
echo ************


REM Read commands from commands.txt and execute them
for /f "tokens=*" %%C in (commands.txt) do (
    set "command=%%C"
    call :run_command "!command!"
    IF %ERRORLEVEL% NEQ 0 (
        set "success=0"
        echo %ip% - Skipping due to failure in command: %%C >> failure.txt
        EXIT /B 1
    )
    timeout /t 2 /nobreak > nul
)

:end_main
IF %success% EQU 1 (
    echo %ip% >> success.txt
	echo %ip% - Process completed successfully
) ELSE (
    echo %ip% >> failure.txt
	echo %ip% - Process encountered errors
)
EXIT /B 0

:run_command
set "command=%~1"
echo Running: %command%
%command% > nul 2>&1
EXIT /B %ERRORLEVEL%