# (c) J.Y.Amihud 2022
# This program is Free Software under the terms of
# GNU General Public License version 3 ( GPL3 ) or
# any later version of the program.

# THIS PROGRAM HAS ABSOLUTELY NO WARRANTY. USE AT
# YOUR OWN RISK. SEE LICENSE FOR DETAILS.

# License could be found in full text on gnu.org/licenses

import os
import json
import sys
import time
import hashlib

# We need to know what folder to backup.

if len(sys.argv) > 1:
    project = sys.argv[1]
else:
    project = input("Project: ")

# To compare changes in files the best way is to look at their
# hashes. They are relatively fast to get. But they will be drastically
# different if the files have at least some differences.
    
def hash_file(f):
    try:
        BLOCKSIZE = 65536
        hasher = hashlib.md5()
        with open(f, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher.update(buf)
                buf = afile.read(BLOCKSIZE)
        return str(hasher.hexdigest())
    except:
        return "FOLDER"

# This function walks ( recursively ) through the folder of the project,
# finds every un-backed up blend-file. And backs it up.

def main():
    for i in os.walk(project):
        for b in i[2]:

            
            if b.endswith(".blend") and "_backup" not in b:
                HASH = hash_file(i[0]+"/"+b)
                F = open(i[0]+"/"+b, "rb")
                F = F.read()
                if not F:
                    print(b, "from", i[0].replace(project, ""), " seems corrupted! Skipping!")
                    continue
                BACKNAME = b[:-6]+"_backup.blend"
                if os.path.exists(i[0]+"/"+BACKNAME):
                    BACKHASH = hash_file(i[0]+"/"+BACKNAME)
                else:
                    BACKHASH = "NO FILE"
                if BACKHASH != HASH:
                    print("Backing up:", b, "from", i[0].replace(project, ""), "...")
                    #F = open(i[0]+"/"+b, "rb")
                    S = open(i[0]+"/"+BACKNAME, "wb")
                    S.write(F)
                    S.close()


# Main loop ( 30 seconds intervals )

while True:

    try:
        with open(project+"/backup_data.json") as f:
            backup_data = json.load(f)
    except:
        backup_data = {}

    backup_data["lastcheck"] = int(time.time())

    with open(project+"/backup_data.json", "w") as f:
        json.dump(backup_data, f, indent=4)
    
    print("Counting another 30 seconds...")
    time.sleep(30)
    print("Checking for changed files...")
    main()
