#!/usr/bin/env python3

# updatelocal.py
# During a BIRCH update, this script checks to make sure
# that all files found in the new copy of $BIRCH/local-generic
# are also present in the existing $BIRCH/local directory.
# Files not found in $BIRCH/local are copied from $BIRCH/local-generic
#

# Set variables for local-generic, local, and current
# directories

import os, os.path, sys, shutil

def update_local():
    UPDIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
    LOCAL = os.path.join(UPDIR, "local")
    LOCALGENERIC = os.path.join(UPDIR, "local-generic")
    print ("LOCAL        " + LOCAL)
    print ("LOCALGENERIC " + LOCALGENERIC)
    newlocalfiles = open("NewLocalFiles.list")

    #---------------------------------------------------------------------------
    # When a directory is not found, copy whole directory
    # in a single step. Otherwise, copy one file at a time.
    for name in newlocalfiles:

        # Note: we have to check to see if $name is a link FIRST, before checking
        # to see if it is a file or directory. Apparently, the shell considers a
        # link to also be a file, so
        # -f $LOCALGENERIC/$name would be true for a link.
        name = name.strip()
        gen_name = os.path.join(LOCALGENERIC, name)
        local_name = os.path.join(LOCAL, name)

        if os.path.exists(gen_name) :
            if not os.path.exists(local_name):
                # symbolic link
                if os.path.islink(gen_name):
                    print ('Copying link ' + gen_name)
                    os.symlink(os.readlink(gen_name),local_name)
                # directory
                elif os.path.isdir(gen_name):
                    print ('Copying directory ' + gen_name)
                    shutil.copytree(gen_name, local_name)
                #file
                else:
                    print ('Copying file ' + gen_name)
                    # shutil.copy2 preserves metadata, such as date of file creation.
                    # shutil.copy does not.
                    shutil.copy2(gen_name, local_name)

    newlocalfiles.close()

if __name__=="__main__":
    update_local()
