@echo off
setlocal ENABLEDELAYEDEXPANSION

:: Define the root input directory
SET "INPUT=%~dp0vault_data\in"

:: Define the destination directory
SET "DESTINATION=%~dp0vault_data\out"

:: Define the error directory
SET "ERRORS=%~dp0vault_data\error"

:: Define the credentials configuration
SET "CONFIG=%~dp0virtru-creds.json"

:: Writes out console summary to a file upon completion
SET "SUM=%~dp0logs\summary.log"

:: Ensure the destination directory exists
if not exist "%DESTINATION%" mkdir "%DESTINATION%"

:: Move and rename .tdf files from subdirectories to the root of "in"
pushd "%INPUT%"
for /R %%G IN (*.tdf) do (
    set "filePath=%%G"
    set "fileName=%%~nxG"
    set "subDirName=%%~pG"
    set "subDirName=!subDirName:~1,-1!"
    for %%H in ("!subDirName!") do set "subDirName=%%~nxH"

    if not "%%~dpG"=="%INPUT%" (
        set "newFileName=!subDirName!_!fileName!"
        echo Moving and renaming "%%G" to "%INPUT%\!newFileName!"
        move "%%G" "%INPUT%\!newFileName!"
     )
)
popd

:: Bulk decrypt everything in the "in" directory
echo Starting bulk decryption...
%~dp0win-x64\virtru.console.exe bulk-decrypt -a -s "%INPUT%" -d "%INPUT%" -c "%CONFIG%" -e "%ERRORS%" -w "%SUM%"
echo Bulk decryption completed.

:: Move decrypted files (and .tdf files if still present) to the corresponding folders in the "out" structure
pushd "%INPUT%"
for %%G IN (*.*) do (  
    set "fileName=%%~nG"
    
    :: Check if file name contains underscore (assuming decrypted files and .tdf files have it after renaming)
    echo !fileName! | findstr /C:"_" >nul 2>&1
    if !ERRORLEVEL! equ 0 (
        :: Extract the original subfolder name from the file name
        for /f "tokens=1,* delims=_" %%H in ("!fileName!") do (
            set "subDirName=%%H"
            set "originalFileName=%%I"
        )

        :: Construct the target directory path
        set "targetDir=%DESTINATION%\!subDirName!"
        if not exist "!targetDir!" mkdir "!targetDir!"

        :: Move the file to the "out" directory, preserving the original file extension
        echo Moving decrypted file "%%G" to "!targetDir!\%%~nxG"
        move "%%G" "!targetDir!\%%~nxG"
    ) else (
        echo Skipping: "%%G" does not match the expected naming convention.
    )
)
popd

echo Process completed. All decrypted .tdf files have been moved to the corresponding folders in %DESTINATION%.

popd