@echo off
set FTPSETTINGS=..\custom\ftpsettings.cmd
set LOCALSIZE=localsize
set REMOTESIZE=remotesize

rem ===================
rem CONFIGFILE CHECK
rem ===================

if NOT EXIST %FTPSETTINGS% (
  echo.
  echo ERROR: %FTPSETTINGS% NOT FOUND
  echo.
  echo --- please create it as follows ---
  echo set FTP_SERVER=example.com
  echo set FTP_PATH=/path/to/directory
  echo set FTP_USER=myuser
  echo set FTP_PASS=mypass
  exit /b
)

rem ===================
rem COMMANDLINE CHECKS
rem ===================

IF %1.==. GOTO USAGE
rem removing extension ...
set LISTFILE=%~n1
rem adding extension again ...
set LISTFILE=%LISTFILE%.csv

IF NOT EXIST %LISTFILE% (
  echo ERROR: %LISTFILE% not found!
  exit /b
)

echo.
echo loading settings ...
call %FTPSETTINGS%
echo ++++++++++++++++++
echo FTP_SERVER=%FTP_SERVER%
echo FTP_PATH=%FTP_PATH%
echo FTP_USER=%FTP_USER%
echo FTP_PASS=xxxxxx
echo ++++++++++++++++++
echo.

echo disabling Windows defender for PATH [ %USERPROFILE% ] ...
powershell -inputformat none -outputformat none -NonInteractive -Command Add-MpPreference -ExclusionPath %USERPROFILE%
echo.

echo using list [ %LISTFILE% ] ...

rem ###################################
rem MAIN loop ( DOWNLOAD from ftp ) ...
rem ###################################

FOR /F "tokens=1,2 delims=, " %%E in (%LISTFILE%) do (

  call :cleanup

  rem get local file size ...
  FORFILES /M %%F /C "cmd /C echo Content-Length: @fsize >%LOCALSIZE%"
  
  rem get remote file size ...
  curl -u %FTP_USER%:%FTP_PASS% -s -I ftp://%FTP_SERVER%/%FTP_PATH%/%%F | findstr Content-Length >%REMOTESIZE%

  call :compare %%F
)
GOTO :cleanup
GOTO :END

:compare
rem COMPARE both ...
fc /W %LOCALSIZE% %REMOTESIZE% 1>nul 2>nul

if %ERRORLEVEL% GTR 0 (

  rem get it with curl ...
  echo.
  echo getting: [ %1 ]
  curl -u %FTP_USER%:%FTP_PASS% -L ftp://%FTP_SERVER%/%FTP_PATH%/%1 --output %1

  rem success ?
  if NOT EXIST %1 (
    echo ERROR: couldn't get %1!
  ) else (
    rem check size (it SHOULD NOT be 0!)
    FORFILES /M %1 /C "cmd /C if @fsize EQU 0 echo ERROR: file @relpath is zero size!"
  ) 

) else (
  echo OK. File [ %1 ] is same size.
)
goto :eof

:cleanup
del /F /Q remotesize 2>nul
del /F /Q localsize 2>nul
goto :eof

:USAGE
echo "usage: %0 <LISTFILE>"
echo   LISTFILE = basic, browser, optional or other
echo.
goto :END

rem =====
rem END
rem =====
:END