SETLOCAL ENABLEDELAYEDEXPANSION
@echo off

:: downloads then deletes ftp files from the given location

set server=ftp.cubi.ca
set username=CP_569
set password=CP_569
:: no trailing / on fetch dir path
set fetch_directory=.
:: no trailing \ on target dir path
set target_dir=C:\Synsoft\Fichier_Entrant\Cubi_Dispill_Master
set temp_script_file=ftp_script.txt
set temp_dir_list=ftp_file_list.txt

:: create temp file with ftp script to output file list
echo open %server%> %temp_script_file%
echo %username%>> %temp_script_file%
echo %password%>> %temp_script_file%
echo mdir %fetch_directory%/*__* %temp_dir_list% >> %temp_script_file%
echo y >> %temp_script_file%
echo bye >> %temp_script_file%

:: now run the script with ftp
ftp -s:%temp_script_file%

:: now we have a list of the files in the ftp directory

:: now make a script from the file listing to copy each file.
echo open %server% > %temp_script_file%
echo %username%>> %temp_script_file%
echo %password%>> %temp_script_file%
echo. >> %temp_script_file%
echo lcd %target_dir%  >> %temp_script_file%
:: copy each file to a dated file locally
for /F "tokens=9" %%i in (%temp_dir_list%) do (
SET get_file=%%i
echo binary >> %temp_script_file%
echo get %fetch_directory%/!get_file:~0,-1!  "%target_dir%\!get_file:~0,-1!" >> %temp_script_file%
echo rename %fetch_directory%/!get_file:~0,-1! %fetch_directory%/Done/!get_file:~0,-1!>> %temp_script_file%
)
echo bye >> %temp_script_file%

:: now run the new script
ftp -s:%temp_script_file%

::remove temporary script files
del %temp_dir_list%
del %temp_script_file%