import subprocess
import time
import datetime

backups = {
    "__GITHUB":"admin@192.168.77.106:/share/Data/__GITHUB",
    "Photo":"admin@192.168.77.106:/share/Photo/Years" 
}

for b in backups:
    SOURCE_DIR=backups[b]
    now = datetime.datetime.now()
    BACKUP_DIR="/srv/dev-disk-by-uuid-02fbe97a-cd9a-4511-8bd5-21f8516353ee/{}".format(b)
    DATETIME = now.strftime("%Y-%m-%d_%H:%M:%S")
    BACKUP_PATH="{}/{}".format(BACKUP_DIR, DATETIME)
    LATEST_LINK="{}/latest".format(BACKUP_DIR)


    cmnd = "mkdir -p {}".format(BACKUP_DIR)
    status, output = subprocess.getstatusoutput(cmnd)
    print(cmnd)

    #cmnd = "rsync -av --delete {}/ --link-dest {} --exclude=\".cache\" {}".format(SOURCE_DIR, LATEST_LINK, BACKUP_PATH)
    cmnd = ["rsync", '--info=progress2', "-avz", "--delete", SOURCE_DIR, "--link-dest",  LATEST_LINK, "--exclude=\".cache\"",  BACKUP_PATH]
    print(cmnd)

    #run_list = ['rsync', '--info=progress2', '-a', 'src/', 'dest/']
    # with subprocess.Popen(
    #     cmnd, stdout=subprocess.PIPE, bufsize=1, text=True
    # ) as process:
    #     for line in iter(p.stdout.readline, b''):
    #         print(line.strip())
    


    process = subprocess.Popen(cmnd,
                            stdout=subprocess.PIPE)

    while process.poll() is None:
        line = process.stdout.readline()
        l = line.splitlines()
        i = -1
        a = len(l)
        #print(l[-1])
        time.sleep(3)
        print(len(l))
        while True:
            for line in reversed(l):
                print(len(line.split()))
                e = str(line).split()
                if len(e) > 4:
                    print(e[2])
                    print(line)
                    break
            break
            
        # print(l[-1])
        # #print(str(line))
        # time.sleep(3)
    #print(cmnd)
    #status, output = subprocess.getstatusoutput(cmnd)
    # rsync -av --delete \
    # "${SOURCE_DIR}/" \
    # --link-dest "${LATEST_LINK}" \
    # --exclude=".cache" \
    # "${BACKUP_PATH}"
    cmnd = "rm -rf {}".format(LATEST_LINK)
    print(cmnd)
    status, output = subprocess.getstatusoutput(cmnd)
    
    cmnd = "ln -s {} {}".format(BACKUP_PATH, LATEST_LINK)
    print(cmnd)
    status, output = subprocess.getstatusoutput(cmnd)