# Extract NMUK Interface Files from Stonebranch Server

import ftplib
import os

from datetime import datetime

# Get today's date
today = datetime.today()

# Format the date as YYMMDD
formatted_date = today.strftime('%y%m%d')

# Get Current Path
dir_path = os.path.dirname(os.path.realpath(__file__))

def main():
# set-up ftp connection to iSeries 
#   ftp = ftplib.FTP('172.16.1.3')
    ftp = ftplib.FTP('172.18.25.28')
    ftp.login('ANONYMOUS','VANTEC')
    ftp.cwd('/LIVE/RESILIENCEIN')
    filenames = ftp.nlst('WCS601RESILIENCE_ZONE*.*')
#loop through list of interface files
#    file_path = os.path.join('c:/rrfiles/resilience')
    file_path = os.path.join('a:/NMUK-Resilience')
    for filename in filenames:
        print("file:",filename)
        host_file = os.path.join(file_path, filename)
        try:
            with open(host_file, 'wb') as local_file:
                ftp.retrbinary('RETR ' + filename, local_file.write)
                ftp.delete(filename)
        except ftplib.error_perm:
            pass
    filenames = ftp.nlst('WCS601RESILIENCE_ZONET.D'+formatted_date+'*.*')
#loop through list of interface files
    for filename in filenames:
        print("file:",filename)
        host_file = os.path.join(file_path, filename)
        try:
            with open(host_file, 'wb') as local_file:
                ftp.retrbinary('RETR ' + filename, local_file.write)
                ftp.delete(filename)
        except ftplib.error_perm:
            pass
    filenames = ftp.nlst('WCS601RESILIENCE_ZONEH.D'+formatted_date+'*.*')
#loop through list of interface files
    for filename in filenames:
        print("file:",filename)
        host_file = os.path.join(file_path, filename)
        try:
            with open(host_file, 'wb') as local_file:
                ftp.retrbinary('RETR ' + filename, local_file.write)
                ftp.delete(filename)
        except ftplib.error_perm:
            pass
    filenames = ftp.nlst('WCS601RESILIENCE_RANS.D'+formatted_date+'*.*')
#loop through list of interface files
    for filename in filenames:
        print("file:",filename)
        host_file = os.path.join(file_path, filename)
        try:
            with open(host_file, 'wb') as local_file:
                ftp.retrbinary('RETR ' + filename, local_file.write)
                ftp.delete(filename)
        except ftplib.error_perm:
            pass 
    filenames = ftp.nlst('WCSRESILIENCE_BOXES_OTHER.D'+formatted_date+'*.*')
#loop through list of interface files
    for filename in filenames:
        print("file:",filename)
        host_file = os.path.join(file_path, filename)
        try:
            with open(host_file, 'wb') as local_file:
                ftp.retrbinary('RETR ' + filename, local_file.write)
                ftp.delete(filename)
        except ftplib.error_perm:
            pass 
    ftp.quit()
    
if __name__ == '__main__':
    main()