@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
    IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params= %*
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------  

adb disconnect
adb usb
ping 127.0.0.1 -n 6 > nul
adb tcpip 5555
ping 127.0.0.1 -n 6 > nul
for /f "tokens=9 delims= " %%i in ('adb shell ip route') do set QuestIP=%%i
adb connect %QuestIP%:5555


echo ============================================
set /p DUMMY=Now disconnect USB from Quest and press Enter to continue.

for /f "tokens=1 delims=." %%i in ("%QuestIP%") do set ipa=%%i
for /f "tokens=2 delims=." %%i in ("%QuestIP%") do set ipb=%%i
for /f "tokens=3 delims=." %%i in ("%QuestIP%") do set ipc=%%i
set net=%ipa%.%ipb%.%ipc%

netstat -anb > netstat_output.txt

for /f "tokens=1 delims=:" %%# in ('findstr /n  /c:"OVRServer_x64.exe" "netstat_output.txt"') do (
    set "line=%%#"
    goto :break
)
:break
set /a prevLine=line-2

more +%prevLine% netstat_output.txt | findstr /c:"LISTENING" > tmp.txt
for /f "tokens=2 delims=:" %%a in (tmp.txt) do (
  echo %%a > tmp2.txt
  for /f "tokens=1 delims= " %%b in (tmp2.txt) do (
  set "port=%%b"
  goto :port
)
)
:port
del netstat_output.txt
del tmp.txt
del tmp2.txt

set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
echo Network Connection Test
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
 echo %%f | findstr /c:%net% >> ippc.txt
)
for /f %%a in (ippc.txt) do set ippc=%%a
del ippc.txt

adb shell am start -a android.intent.action.VIEW -d "xrstreamingclient://%ippc%:%port%" com.oculus.xrstreamingclient