# -*- coding: utf-8 -*-
"""
Created on Thu Mar  6 15:18:09 2025

@author: CALLISTO
"""

# -*- coding: utf-8 -*-
"""
Created on Fri Apr 19 14:32:53 2024
https://www.tutorialspoint.com/python_network_programming/python_sftp.htm
https://stackoverflow.com/questions/68180157/upload-all-files-from-local-folder-with-specific-extension-to-sftp-server-using
https://www.datacourses.com/how-to-upload-files-to-sftp-server-in-python-2218/

@author: cmonstein
"""

import ftplib
import paramiko
import os
import gzip
import datetime
import shutil
import time

#-------------------------------------------------------------------------------

sourcepath  = 'c:/Callisto-01/FITfiles/'
destination = 'c:/Callisto-01/FITfiles/'
backupdir   = 'c:/Callisto-01/FITbackup/'
ForceBackup = True

#-------------------------------------------------------------------------------

def gzip_file(src_path, dst_path):
    with open(src_path, 'rb') as src, gzip.open(dst_path, 'wb') as dst:
        for chunk in iter(lambda: src.read(4096), b""):
            dst.write(chunk)

#-------------------------------------------------------------------------------

def uploadspain(myfile):
    #paramiko.util.log_to_file("paramiko.log")

    host,port = "astrodoncel.uah.es",3974

    transport = paramiko.Transport((host,port))

    username,password = "UsernameAlcala","PasswordAlcala"
    transport.connect(None,username,password)

    sftp = paramiko.SFTPClient.from_transport(transport)

    head,filename = os.path.split(myfile)
    remotepath = "/ftpfolder/"+ filename
    tmppath = remotepath + '.tmp'
    #localpath = filename
    localpath = myfile
    #print (localpath,remotepath)
    try:
        # print('SFTPinput:',localpath)
        # print('TMPpath:',tmppath)
        # print('remotepath:',remotepath)
        sftp.put(localpath,tmppath)
        time.sleep(1)
        sftp.rename(tmppath,remotepath)
    except:
        print("File already exists at sftp-server, cannot be uploaded!") 

    if sftp: sftp.close()
    if transport: transport.close()

#-------------------------------------------------------------------------------

def uploadfhnw(myfile):
    server   = "ftpexchange.cs.technik.fhnw.ch"
    username = "UsernameFHNW"
    password = "PasswordFHNW"

    ftp = ftplib.FTP(server)
    ftp.login(username, password)
    ftp.set_pasv(True)
    head,filename = os.path.split(myfile)
    buffer = open(myfile, 'rb') 
    ftp.storbinary('STOR ' + filename+'.tmp', buffer)
    time.sleep(1)
    ftp.rename(filename+'.tmp',filename)
    buffer.close()

#-------------------------------------------------------------------------------
# perform backup in case selected

def DoBackup(file):
    year  = datetime.datetime.now().year
    month = datetime.datetime.now().month
    day   = datetime.datetime.now().day
    destination = backupdir +'{:04d}'.format(year) + '/{:02d}'.format(month) +'/{:02d}'.format(day)
    # print ('input:',file)
    # print ('Backup now to: ',destination)

    if not os.path.exists(destination):
        os.makedirs(destination)
    try:
        shutil.move(file,destination)
    except:
        print("File already exists, cannot be moved to backup-folder and will therefore be locally deleted!") 
        os.remove(sourcepath + file)

#-------------------------------------------------------------------------------
# Upload files

files = os.listdir(sourcepath)

for file in files:
    # print ('Found: ',file)
    if file.endswith('.fit'):
        filegz = destination + file+'.gz'
        #print('Ziel:',filegz)
        infile = sourcepath + file
        #print('input:',infile)
        gzip_file(infile, filegz)
        uploadspain(filegz)
        uploadfhnw(filegz)

        if ForceBackup:
            DoBackup(filegz)
        else:
            os.remove(filegz)

        os.remove(infile)

#-------------------------------------------------------------------------------
