import ftplib
import ssl,os

# FTP credentials
ftp_host = 'ftp.dataforsyningen.dk'
ftp_user = 'luis'
ftp_password = 'BBk!@aFX-8nfTYC'

# Directory on the FTP server from which to download files
ftp_directory = '/dhm_danmarks_hoejdemodel/DTM'

# Local directory where files will be saved
local_directory = '/mnt/vault/carto_private/01_ORIGINAL/world/europe/denmark/dtm/dtm/'

# Ensure the local directory exists
#os.makedirs(local_directory, exist_ok=True)

def download_ftp_directory(ftp, remote_dir, local_dir):
    # Change to the remote directory
    ftp.cwd(remote_dir)

    # Get a list of files in the remote directory
    file_names = ftp.nlst()

    for file_name in file_names:
        local_file_path = os.path.join(local_dir, file_name)
        if not os.path.exists(local_file_path):
            with open(local_file_path, 'wb') as local_file:
                ftp.retrbinary(f'RETR {file_name}', local_file.write)
            print(f'Downloaded: {file_name}')

# Create an FTP_TLS object and configure it for implicit TLS
ftp = ftplib.FTP_TLS()
ftp.ssl_version = ssl.PROTOCOL_TLS_CLIENT
ftp.connect(ftp_host, 990)  # Use port 990 for implicit TLS
ftp.login(ftp_user, ftp_password)

# Secure the data connection with TLS
ftp.prot_p()

# Download the directory
download_ftp_directory(ftp, ftp_directory, local_directory)

# Close the connection
ftp.quit()

print("All files have been downloaded.")
