#!/usr/bin/env python3

import sys
import os
import hashlib
import time

def usage():
    print("wrong args")
    print("ndfs cp <filename> <targetpath>")

def freader(filename, size):
    f = open(filename, "rb")
    while True:
        data = f.read(size)
        if not data:
            break
        yield data

def hashfile(filename, hashobj):
    size = hashobj.block_size
    for data in freader(filename, size):
        hashobj.update(data)
    return hashobj.hexdigest()

if __name__ == "__main__":
    filename = sys.argv[1]
    targetpath = sys.argv[2]
    targetfilename = targetpath+"/"+filename
    if os.path.exists(targetfilename):
        print("file exists")
        exit(1)
    print("will copy", filename, "to", targetpath)
    if not os.path.exists(targetpath+"/.ndfs"):
        print(targetpath, "is not ndfs folder")
        exist(1)
    blobpath = targetpath+"/.ndfs/blob/"
    hashnumber = hashfile(filename, hashlib.sha1())
    print(filename, hashnumber)
    lead = hashnumber[:2]
    try:
        print("mkdir", blobpath+lead)
        os.makedirs(blobpath+lead)
    except:
        pass
    blobfilename = blobpath+lead+"/"+hashnumber
    if os.path.exists(blobfilename):
        print("blob exists")
        log = "{}: {} symlink to {}\n".format(time.asctime(), filename, blobfilename)
        open(targetpath+"/.ndfs/ndfs.log","a").write(log)
    else:
        with open(blobfilename,"wb") as f:
            for data in freader(filename, 4*1024):
                f.write(data)
        log = "{}: {} copy to {}\n".format(time.asctime(), filename, blobfilename)
        open(targetpath+"/.ndfs/ndfs.log","a").write(log)
    rpath = os.path.relpath(os.path.realpath(blobfilename), os.path.realpath(targetpath))
    os.symlink(rpath, targetpath+"/"+filename)
