@echo off
if  exist OA3.bin  del OA3.bin
if  exist key.log  del key.log
if  exist Config.dms  del Config.dms

AMIDEWINx64 /DMS

powershell -ExecutionPolicy Bypass -File "getkey.ps1"

set "activeKeyFile=key.log"
if not exist %activeKeyFile% (
	Process.exe 1 "No found any key file name: %activeKeyFile%"
		goto END
)	

rem;;从文件最后一行读取字符串
set "activeKey="
for /F "delims=" %%i in ('type %activeKeyFile% ^| wgrep -v "^$" ^| wtail.exe -n1 ^| wtr -d " " ^| wtr "[a-z]" "[A-Z]"') do ( set "activeKey=%%i" )
rem;;for /F "delims=" %%i in ('echo %activeKey%^| wtr -d " " ^| wtr "[a-z]" "[A-Z]" ') do ( set "activeKey=%%i" )

rem;;判断字符串的格式是是否是: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
echo %activeKey% | wgrep -iwEq "([a-z0-9]{5})((-[a-z0-9]{5}){4})"
if %errorlevel% NEQ 0  (
	Process.exe 1 "Error format of key \"%activeKey%\""
	rem;; 错误的格式则直接删除最后一行
	wsed -i "$s/[A-Za-z0-9]\|[[:punct:]]\|^$//g"  %activeKeyFile%
	wsed -i "/^$/d" %activeKeyFile%
  del sed*
	goto END  
)

if not exist mode_OA3.bin (
	Process.exe 1 "No found any bin file name: mode_OA3.bin"
	goto END 
) else (
	copy mode_OA3.bin OA3.bin /y >nul
)
wsed.exe -i "s/[A-Z0-9]\{5\}-[A-Z0-9]\{5\}-[A-Z0-9]\{5\}-[A-Z0-9]\{5\}-[A-Z0-9]\{5\}/%activeKey%/g" OA3.bin
wgrep -q "%activeKey%" OA3.bin
if %errorlevel% EQU 0  (
	Process.exe 0 "The key \"%activeKey%\" has been append to OA3.bin"
	rem;;生成正确的bin档案后则直接删除最后一行
	wsed -i "$s/[A-Za-z0-9]\|[[:punct:]]\|^$//g"  %activeKeyFile%
	wsed -i "/^$/d" %activeKeyFile%
	del sed* >nul
) else (
	Process.exe 1 "Fail to append key \"%activeKey%\" to OA3.bin"
	goto END 
)


:END

::for /f "skip=4 delims=" %%i in ('type "Config.dms"') do echo %%i>>Config.txt
setlocal enabledelayedexpansion

set "input=Config.dms"
set "output=Config.txt"

>"%output%.tmp" (
    set "currentSection="
    set "prevSection="
    for /f "usebackq delims=" %%a in ("%input%") do (
        set "line=%%a"
        
  
        if "!line:~0,1!"=="[" (
            set "prevSection=!currentSection!"
            set "currentSection="
            
            if "!line!"=="[System]" (
                set "currentSection=System"
                echo [System]
            ) else if "!line!"=="[BaseBoard]" (
                set "currentSection=BaseBoard"
 
                if defined prevSection echo.
                echo [BaseBoard]
            )
        )
        
 
        if "!currentSection!"=="System" (
            if "!line:~0,9!"=="SerialNum" echo !line!
            if "!line:~0,4!"=="UUID" echo !line!
        )
        
 
        if "!currentSection!"=="BaseBoard" (
            if "!line:~0,9!"=="SerialNum" echo !line!
        )
    )
)

 
move /y "%output%.tmp" "%output%" >nul
endlocal

del /f /q Config.dms
ren Config.txt Config.dms

copy Restore.bat ..\