@echo off
echo.
echo Braswell BIOS updater - Windows x64 Version
echo.

setlocal enabledelayedexpansion

::Check if a valid bios file is passed
if "%1"=="" goto ef1
if EXIST %1 goto start
echo   %1 does not exist, please enter the right official bios.
goto end

:start

::Save current Sleep button and Lid action options

::Read the power configuration currently active
for /f "tokens=2 delims=:(" %%i in ('powercfg -getactivescheme ^| findstr "[0-9a-z]*-[0-9a-z]*-[0-9a-z]*-[0-9a-z]*-[0-9a-z]*"') do set ACTIVEGUID=%%i

set SLP_FLAG=0
set LID_FLAG=0

::Scan the Powercfg query command output
for /f "tokens=2 delims=:" %%i in ('powercfg -q !ACTIVEGUID! SUB_BUTTONS') do (
  ::Search for the Sleep Button GUID
  Echo %%i|FindStr /R "96996bc0-ad50-47ec-923b-6f41874dd9eb" >NUL
  If "!ERRORLEVEL!" EQU "0" set SLP_FLAG=2
  
  ::Search for the Lid GUID
  Echo %%i|FindStr /R "5ca83367-6e45-459f-a27b-476b1d01c936" >NUL
  If "!ERRORLEVEL!" EQU "0" set LID_FLAG=2
  
  echo %%i|FindStr /R "[0-9]x[0-9]*" >NUL
  If "!ERRORLEVEL!" EQU "0" (
    ::Search the Sleep Button settings
    If "!SLP_FLAG!" GTR "0" (
      set SLP_CURRENTSETTINGAC=!SLP_CURRENTSETTINGDC!
      set SLP_CURRENTSETTINGDC=%%i
      set /A SLP_FLAG=!SLP_FLAG!-1
    )
  
    ::Search the Lid settings
    If "!LID_FLAG!" GTR "0" (
      set LID_CURRENTSETTINGAC=!LID_CURRENTSETTINGDC!
      set LID_CURRENTSETTINGDC=%%i
      set /A LID_FLAG=!LID_FLAG!-1
    )
  )
)

set SLP_CURRENTSETTINGAC=%SLP_CURRENTSETTINGAC:~-1%
set SLP_CURRENTSETTINGDC=%SLP_CURRENTSETTINGDC:~-1%
set LID_CURRENTSETTINGAC=%LID_CURRENTSETTINGAC:~-1%
set LID_CURRENTSETTINGDC=%LID_CURRENTSETTINGDC:~-1%

::Disable Sleep button and Lid
powercfg -SETACVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 96996bc0-ad50-47ec-923b-6f41874dd9eb 0
powercfg -SETDCVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 96996bc0-ad50-47ec-923b-6f41874dd9eb 0
powercfg -SETACVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 5ca83367-6e45-459f-a27b-476b1d01c936 0
powercfg -SETDCVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 5ca83367-6e45-459f-a27b-476b1d01c936 0
powercfg -setactive %ACTIVEGUID%

::Program new bios
H2OFFT-Wx64 %1 -ALL -N
H2OFFT-Wx64 %1 -SPN -N

::Restore original Sleep button amd Lid settings
powercfg -SETACVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 96996bc0-ad50-47ec-923b-6f41874dd9eb %SLP_CURRENTSETTINGAC%
powercfg -SETDCVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 96996bc0-ad50-47ec-923b-6f41874dd9eb %SLP_CURRENTSETTINGDC%
powercfg -SETACVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 5ca83367-6e45-459f-a27b-476b1d01c936 %LID_CURRENTSETTINGAC%
powercfg -SETDCVALUEINDEX !ACTIVEGUID! SUB_BUTTONS 5ca83367-6e45-459f-a27b-476b1d01c936 %LID_CURRENTSETTINGDC%
powercfg -setactive %ACTIVEGUID%

goto message

:ef1

echo.
echo   Please enter the BIOS file parameter
echo.
goto end

:message
echo.
echo   BIOS updated, please perform a full reboot for completing the operation
echo.
goto end

:end
