@echo off
setlocal

REM --- Paths relative to this script ---
REM %~dp0 is the path to the directory where this .bat file is located (e.g., Z:\Music\Navidrome\)

set RCLONE_EXE=%~dp0.sync\bin\rclone.exe
set RCLONE_CONFIG=%~dp0.sync\config\rclone.conf
set LOG_DIR=%~dp0.sync\logs

REM --- Create a unique log file name with timestamp (YYYYMMDD_HHMMSS) ---
REM Get date parts (assuming Russian locale DD.MM.YYYY or similar that allows these extractions)
set DAY_PART=%date:~0,2%
set MONTH_PART=%date:~3,2%
set YEAR_PART=%date:~6,4%

REM Get time parts and ensure two digits for hour, minute, second
set HH=%time:~0,2%
if "%HH:~0,1%" == " " set HH=0%HH:~1,1%
set MIN=%time:~3,2%
if "%MIN:~0,1%" == " " set MIN=0%MIN:~1,1%
set SS=%time:~6,2%
if "%SS:~0,1%" == " " set SS=0%SS:~1,1%

set TIMESTAMP=%YEAR_PART%%MONTH_PART%%DAY_PART%_%HH%%MIN%%SS%
set LOG_FILE=%LOG_DIR%\rclone_sync_%TIMESTAMP%.log

set SOURCE_REMOTE=smb_music:media/music
set DEST_LOCAL=%~dp0Library

REM --- Argument for dry-run ---
set DRY_RUN_FLAG=
IF /I "%~1" == "--dry-run" (
    echo Dry run mode enabled. No changes will be made.
    set DRY_RUN_FLAG=--dry-run
)
IF /I "%~1" == "-n" (
    echo Dry run mode enabled. No changes will be made.
    set DRY_RUN_FLAG=--dry-run
)

REM --- Create log directory if it doesn't exist ---
if not exist "%LOG_DIR%" (
    echo Creating log directory: %LOG_DIR%
    mkdir "%LOG_DIR%"
)

echo Starting Rclone Music Sync...
echo Source: %SOURCE_REMOTE%
echo Destination: %DEST_LOCAL%
echo Rclone Executable: %RCLONE_EXE%
echo Rclone Config: %RCLONE_CONFIG%
echo Log File will be: "%LOG_FILE%"
if defined DRY_RUN_FLAG echo Mode: Dry Run
echo.

REM --- Rclone sync command ---
"%RCLONE_EXE%" sync "%SOURCE_REMOTE%" "%DEST_LOCAL%" ^
    %DRY_RUN_FLAG% ^
    --config "%RCLONE_CONFIG%" ^
    --checkers=8 ^
    --transfers=8 ^
    --progress ^
    --log-file "%LOG_FILE%" ^
    --log-level INFO

echo.
echo Rclone Music Sync finished.
echo Log file: "%LOG_FILE%"

endlocal
pause