#! /usr/bin/env python3

import os, time, subprocess

def check_ping(hostname = str):
    list_command = list(str('timeout 0.2 ping -c 1 ' + hostname).split())
    response = subprocess.run(list_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # and then check the response...
    if response.returncode == 0:
        return True
    else:
        return False

def rclone_folders_copy(folder_to_sync=list, dest_folder = str, rclone_config_name = str):
    check_list = []
    for sync_folder in folder_to_sync:
        print("Hole Datein", 'rclone:' + sync_folder, "...")
        list_command = list(str('rclone copy '+ rclone_config_name + ':' + sync_folder + ' ' + dest_folder + os.sep + sync_folder + ' --update --create-empty-src-dirs').split())
        command = subprocess.run(list_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        if command.returncode == 0:
                check_list.append(True)
        elif command.returncode > 0:
                check_list.append(False)
                print("Folder", "rclone:" + sync_folder , "not exist")
        print("Kopiere Datein", dest_folder + os.sep + sync_folder, "..."  )

        list_command = list(str('rclone copy ' + dest_folder + os.sep + sync_folder  + ' ' + rclone_config_name + ':' + sync_folder + ' --update --create-empty-src-dirs').split())
        command = subprocess.run(list_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        if command.returncode == 0:
                check_list.append(True)
        elif command.returncode > 0:
                check_list.append(False)
                print("Folder", dest_folder + os.sep + sync_folder , "not exist")   
    for check in check_list:
        if check is False:
            return False
    return True

def run_rclone_sync(folders_syc = list, dest_folder = str, rclone_config_path = str):
    print("Check online status von", nextcloud_server)
    for check_count in range(1,10):
        if check_ping(hostname=nextcloud_server) is True:
            print(nextcloud_server, "ist erreichbar...")
            if rclone_folders_copy(folder_to_sync=folders_syc, dest_folder=dest_folder, rclone_config_name=rclone_config_path) is True:
                print("Sync erfolgreich")           
            else:
                print("Sync nicht erfolgreich !!")
            break
        print(check_count, "warte 10 Sekunden..",sep=" ")
        time.sleep(10)
    else:
        raise RuntimeError(nextcloud_server + " not connect")
     

if __name__ == "__main__":
    nextcloud_server = "schlaubistechtalk.de"
    dest_folder = os.environ["HOME"] + os.sep + ".nextcloud"
    folder_to_sync_manuell = ['frei']
    folder_to_sync_decrypt = ['sec']
    
    run_rclone_sync(folders_syc=folder_to_sync_manuell, dest_folder=dest_folder, rclone_config_path='rclone')
    run_rclone_sync(folders_syc=folder_to_sync_decrypt, dest_folder=dest_folder, rclone_config_path='secrclone')
    


