@echo off
chcp 65001 >nul 2>&1
setlocal enabledelayedexpansion
set "ISDEBUG="
@REM set "ISDEBUG=true"
set "DEFAULT_COLOR=Cyan"
set "VERSION_NUM=1.1.0"
set "VERSION_DATE=29.04.2026"
@REM set "ISDEBUG=false"
set "SCRIPT_DIR=%~dp0"
set "SCRIPT_NAME=%~n0"
set "SCRIPT_ETX=%~x0"
set "SCRIPT_FNAME=%~nx0"
set "SCRIPT_PATH=%~dpnx0"
set "DEFAULT_COLOR=Cyan"

set "BASE_URL=http://gper.ru"
REM set "WIN7_URL=%BASE_URL%/win7"
set "GPER_DIR_ROOT=%APPDATA%\gper.ru"
set "GPER_DIR_INSTALL=%GPER_DIR_ROOT%\install"
set "PS_FILE_NAME=002-set-env.ps1"
REM set "PS_FILE_URL=%WIN7_URL%/%PS_FILE_NAME%"
set "PS_FILE_PATH=%SCRIPT_DIR%_scripts\%PS_FILE_NAME%"

set "WIN_VERS="


goto :MAIN

:WAITING
set "WAIT_SEC=%1"
if not defined WAIT_SEC set "WAIT_SEC=2"
call :LOG_PS "Ожидание !WAIT_SEC! сек..."
ping 127.0.0.1 -n !WAIT_SEC! >nul 2>&1
exit /b

:TRIM
set "str=%~1"
:: Удаление ведущих пробелов через цикл
for /f "tokens=* delims= " %%a in ("%str%") do set "str=%%a"
:: Удаление замыкающих пробелов (хитрость с переменной)
:TRIM_TRAILING
if "%str:~-1%"==" " (
    set "str=%str:~0,-1%"
    goto :TRIM_TRAILING
)
set "%~2=%str%"
exit /b

:SHOWBANNER
echo.
set "SS="
set "FSS=*"
for /L %%I in (1,1,35) DO (
@REM echo FIRST%%I
@REM ECHO LAST%%I
set "SS=!SS!="
)
@REM echo !SS!
call :LOG_PS "!SS!"
:: Выводим строки, которые начинаются с "::: "
@REM for /f "delims=: tokens=*" %%a in ('findstr /b ":::" "%~f0"') do echo %%a
for /f "delims=: tokens=*" %%a in ('findstr /b ":::" "%~f0"') do (
    call :LOG_PS "%%a"
)
set "FMSG=Версия: %VERSION_NUM% Дата: %VERSION_DATE%"
call :LOG_PS "!FMSG!"
call :LOG_PS "!SS!"
echo.
exit /b

::: ██████╗  ██████╗  ███████╗ ██████╗ 
::: ██╔════╝ ██╔══██╗ ██╔════╝ ██╔══██╗
::: ██║ ███╗ ██████╔╝ █████╗   ██████╔╝
::: ██║ ██ ║ ██╔═══╝  ██╔══╝   ██╔═██╗
::: ██████╔╝ ██║      ███████╗ ██║ ██║ 
::: ╚════╝   ╚═╝      ╚══════╝ ╚═╝ ╚═╝

:GETWINVER
@REM setlocal enabledelayedexpansion
:: Получаем версию системы через команду 'ver'
set "FMSG_CONST=Определена Windows" 
for /f "tokens=4-5 delims=. " %%i in ('ver') do set VV=%%i.%%j
set "FMSG=[GETWINVER] - VERSION=!VV!"
if defined ISDEBUG call :LOG_PS "!FMSG!"
if "!VV!" == "6.1" (
    set "WIN_VERS=7"
@REM     set "FMSG=!FMSG_CONST!7" 
) else if "!VV!" == "10.0" (
@REM     :: Windows 10 и 11 имеют один номер версии (10.0)
@REM     :: Чтобы их различить, нужно смотреть номер сборки (build)
    for /f "tokens=6 delims=. " %%k in ('ver') do set BB=%%k
    set "BUILD=!BUILD:]=!"
    set "FMSG=[GETWINVER] - BUILD=!BB!"
    if defined ISDEBUG call :LOG_PS "!FMSG!"    
    set "WIN_VERS=10"
    if !BB! GEQ 22000 (
        set "WIN_VERS=11"
    )
) else (
    set "WIN_VERS=WIN_UNKNOWN"
    set "FMSG=Версия Windows не определена" 
)
set "FMSG=[GETWINVER] - WIN_VERS=!WIN_VERS!"
if defined ISDEBUG call :LOG_PS "!FMSG!"
set "FMSG=!FMSG_CONST! !WIN_VERS!"
call :LOG_PS "!FMSG!"

exit /b

:RUNASADMIN
:: --- Проверка прав администратора ---
set "LABELNAME=%~0"
if "%ISDEBUG%"=="true" ( 
    call :log_ps "%LABELNAME%"
)
:: Проверка прав администратора через команду net session
net session >nul 2>&1
if %errorLevel% == 0 (
    set "FMSG=Работаем с правами администратора."
    call :log_ps "!FMSG!" "Green"
) else (    
    set "FMSG=Запрашиваем повышение прав..."
    call :log_ps "!FMSG!" "Yellow"
    :: Перезапуск скрипта с использованием PowerShell и глагола RunAs
    powershell -Command "Start-Process -FilePath '%SCRIPT_PATH%' -Verb RunAs"
    exit 
)
@REM echo.
exit /b


:LOG_PS
set "ERRCODE="
set "FMESSAGE=%~1"
set "FCOLOR=%~2"
if not defined FCOLOR (
    set "FCOLOR=%DEFAULT_COLOR%"
)
call :TRIM "%FMESSAGE%" FMSG
@REM echo FMSG=%FMSG%
if "x%FMSG%"=="x" exit /b
powershell -Command "'%FMSG%' -split '`n' | ForEach-Object { Write-Host $_ -ForegroundColor %FCOLOR% }"
set "ERRCODE=%errorLevel%"
@REM echo %ERRCODE%
if %ERRCODE%==0 exit /b
set "ERRCODE=-1"
goto :ERRCODEEXIT 
exit /b


:DOWNLOADFILE
set "ERRCODE=0"
set "FURL=%1"
set "FDST=%2"
set "FMSG=Загрузка !FURL! в !FDST!..."
call :LOG_PS "%FMSG%"
@REM if defined FDST (
@REM     if exist "%FDST%" del "%FDST%" >nul 2>&1
@REM )
@REM pause
call :CALLING GETWINVER
@REM pause
if %WIN_VERS% EQU 7 (
    powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "(New-Object Net.WebClient).DownloadFile('%FURL%', '%FDST%')" >nul 2>&1
    @REM call :LOG_PS "%WIN_VERS%"
) else (
    powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "irm '%FURL%'" >nul 2>&1
    @REM call :CALLING LOG_PS "%WIN_VERS%"
)
set "ERRCODE=%errorLevel%"
@REM echo %ERRCODE%
if %ERRCODE%==0 (
    set "FMSG=Файл !FDST! успешно загружен."
    @REM echo "FMSG=!FMSG!"
    call :LOG_PS "!FMSG!" "Green"
    exit /b
)
set "ERRCODE=-2"
@REM echo %ERRCODE%
goto :ERRCODEEXIT !FURL!
exit /b

:CALLING
set "FLABEL=%~1"
set "FPARAMETR01=%~2"
set "FPARAMETR02=%~3"
set "FPARAMETR03=%~4"
set "ERRCODE=0"

if not defined FPARAMETR (
    set "FMSG=Запуск %FLABEL% без параметров"
) else (
    set "FMSG=Запуск %FLABEL% с параметрами"
)
@REM :: Если нужно добавить метку FLABEL к сообщению
@REM set "FMSG=%FMSG% %FLABEL%"
:: Проверка флага отладки и вызов лога вынесены из блока IF
if defined ISDEBUG call :LOG_PS "%FMSG%"

if defined FPARAMETR03 (
    call :%FLABEL% "%FPARAMETR01%" "%FPARAMETR02%" "%FPARAMETR03%"
) else (
  if defined FPARAMETR02 (
    call :%FLABEL% "%FPARAMETR01%" "%FPARAMETR02%"
  ) else (
    if defined FPARAMETR01 (
        call :%FLABEL% "%FPARAMETR01%"
    ) else (
        call :%FLABEL%
    )
  )
)

set "FMSG=Конец %FLABEL%"
if defined ISDEBUG call :LOG_PS "%FMSG%"

exit /b

:MAIN 
cls
call :CALLING RUNASADMIN
call :CALLING SHOWBANNER
:MYEOF
REM call :CALLING TLSREG
REM if not exist "%GPER_DIR_INSTALL%" mkdir "%GPER_DIR_INSTALL%"
REM call :CALLING DOWNLOADFILE "%PS_FILE_URL%" "%PS_FILE_PATH%"
REM if %ERRCODE% EQU 0 (
if not exist "!PS_FILE_PATH!" (
	set "FMSG=Файла !PS_FILE_PATH! нет"
	call :LOG_PS "!FMSG!" "Red"
	set "ERRCODE=-3"
	goto :ERRCODEEXIT
) else (
	set "FMSG=Запуск !PS_FILE_PATH!"
	call :LOG_PS "!FMSG!" "Yellow"
	REM call :CALLING WAITING 3
)

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$b=[System.IO.File]::ReadAllBytes('!PS_FILE_PATH!'); if(-not($b.Count -ge 3 -and $b[0] -eq 0xEF -and $b[1] -eq 0xBB -and $b[2] -eq 0xBF)){$b=[byte[]](0xEF,0xBB,0xBF)+$b}; [System.IO.File]::WriteAllBytes('!PS_FILE_PATH!',$b)"
echo "powershell.exe -NoProfile -ExecutionPolicy Bypass -Command '!PS_FILE_PATH!'"
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "!PS_FILE_PATH!"


REM )
goto :MYEOF
exit 

:ERRCODEEXIT
set "DESCR=%1"
set "ERRORMSG=Неизвестная ошибка"
@REM echo "DESCR = %DESCR%"
@REM echo "ERRORMSG = %ERRORMSG%"
if "!ERRCODE!" equ "-1" set "ERRORMSG=[!ERRCODE!] Неверный формат записи в лог"
if "!ERRCODE!" equ "-2" set "ERRORMSG=[!ERRCODE!] Ошибка при скачивании файла !DESCR!"
if "!ERRCODE!" equ "-3" set "ERRORMSG=[!ERRCODE!] Отсутствует файл скрипта !PS_FILE_PATH!"
@REM if "%ERRCODE%" equ "3" set "ErrorMsg=[%ERRCODE%] Изменеие политика выполнения PowerShell. `nОшибка: Не удалось изменить политику выполнения PowerShell.`nДальнейшая работа невозможна."
@REM if "%ERRCODE%" equ "4" set "ErrorMsg=Ну и не сильно хотелось. Пока!!!"

@REM Powershell -command '$DD = Get-Date -Format "yyyyMMdd HH:mm:ss"; Write-Host "[$DD] Ошибка Жопа негра" -ForegroundColor Red'
@REM powershell -command '$DD = Get-Date -Format "yyyyMMdd HH:mm:ss"; Write-Host "[$DD] !ERRORMSG!" -ForegroundColor Red'
@REM echo.
@REM echo "DESCR = %DESCR%"
@REM echo "ERRORMSG = %ERRORMSG%"
REM powershell -Command "$DD = Get-Date -Format 'yyyyMMdd HH:mm:ss'; Write-Host "[$DD] $env:ERRORMSG" -ForegroundColor Red"
REM echo "ERRORMSG=!ERRORMSG!"
FOR /F "tokens=*" %%i IN ('powershell -Command "Get-Date -Format 'yyyyMMdd HH:mm:ss'"') DO SET "DD=%%i"
REM echo "DD=%DD%"
REM pause
set "FMSG=[!DD!] !ERRORMSG!"
set "FCOLOR=Red"
powershell -Command "'!FMSG!' -split '`n' | ForEach-Object { Write-Host $_ -ForegroundColor !FCOLOR! }"
goto :MYEOF
exit
@REM exit /b 1

:MYEOF
endlocal
echo "MYEOF"
pause