@echo off
setlocal EnableDelayedExpansion

:: Convert username to lowercase
set "USERNAME_LOWER=%USERNAME%"
for %%a in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
    call set "USERNAME_LOWER=!USERNAME_LOWER:%%a=%%a!"
)
:: Convert uppercase to lowercase using character-by-character replacement
set "USERNAME_LOWER=%USERNAME_LOWER:A=a%"
set "USERNAME_LOWER=%USERNAME_LOWER:B=b%"
set "USERNAME_LOWER=%USERNAME_LOWER:C=c%"
set "USERNAME_LOWER=%USERNAME_LOWER:D=d%"
set "USERNAME_LOWER=%USERNAME_LOWER:E=e%"
set "USERNAME_LOWER=%USERNAME_LOWER:F=f%"
set "USERNAME_LOWER=%USERNAME_LOWER:G=g%"
set "USERNAME_LOWER=%USERNAME_LOWER:H=h%"
set "USERNAME_LOWER=%USERNAME_LOWER:I=i%"
set "USERNAME_LOWER=%USERNAME_LOWER:J=j%"
set "USERNAME_LOWER=%USERNAME_LOWER:K=k%"
set "USERNAME_LOWER=%USERNAME_LOWER:L=l%"
set "USERNAME_LOWER=%USERNAME_LOWER:M=m%"
set "USERNAME_LOWER=%USERNAME_LOWER:N=n%"
set "USERNAME_LOWER=%USERNAME_LOWER:O=o%"
set "USERNAME_LOWER=%USERNAME_LOWER:P=p%"
set "USERNAME_LOWER=%USERNAME_LOWER:Q=q%"
set "USERNAME_LOWER=%USERNAME_LOWER:R=r%"
set "USERNAME_LOWER=%USERNAME_LOWER:S=s%"
set "USERNAME_LOWER=%USERNAME_LOWER:T=t%"
set "USERNAME_LOWER=%USERNAME_LOWER:U=u%"
set "USERNAME_LOWER=%USERNAME_LOWER:V=v%"
set "USERNAME_LOWER=%USERNAME_LOWER:W=w%"
set "USERNAME_LOWER=%USERNAME_LOWER:X=x%"
set "USERNAME_LOWER=%USERNAME_LOWER:Y=y%"
set "USERNAME_LOWER=%USERNAME_LOWER:Z=z%"

:: Set variables
set "DOWNLOAD_URL=https://sig.zedler.de/%USERNAME_LOWER%.zip"
set "SIGNATURES_DIR=%APPDATA%\Microsoft\Signatures"
set "TEMP_ZIP=%TEMP%\%USERNAME_LOWER%_signature.zip"

:: Create signatures directory if it doesn't exist
if not exist "%SIGNATURES_DIR%" mkdir "%SIGNATURES_DIR%"

:: Download the ZIP file using PowerShell
echo Downloading signature from %DOWNLOAD_URL%...
powershell -Command "Invoke-WebRequest -Uri '%DOWNLOAD_URL%' -OutFile '%TEMP_ZIP%' -UseBasicParsing"

if %ERRORLEVEL% NEQ 0 (
    echo Error: Failed to download signature file.
    exit /b 1
)

:: Extract the ZIP file to the Signatures folder
echo Extracting to %SIGNATURES_DIR%...
powershell -Command "Expand-Archive -Path '%TEMP_ZIP%' -DestinationPath '%SIGNATURES_DIR%' -Force"

if %ERRORLEVEL% NEQ 0 (
    echo Error: Failed to extract signature file.
    del "%TEMP_ZIP%" 2>nul
    exit /b 1
)

:: Clean up temporary file
del "%TEMP_ZIP%" 2>nul

echo Signature updated successfully.
endlocal
