# Path: ififuncs.py
# def generate_log(log, what2log):
#     if not os.path.isfile(log):
#         with open(log, "w", encoding='utf-8') as fo:
#             fo.write(time.strftime("%Y-%m-%dT%H:%M:%S ")
#                      + getpass.getuser()
#                      + ' ' + what2log + ' \n')
#     else:
#         with open(log, "a", encoding='utf-8') as fo:
#             fo.write(time.strftime("%Y-%m-%dT%H:%M:%S ")
#                      + getpass.getuser()
#                      + ' ' + what2log + ' \n')
# 
# Path: ififuncs.py
# def manifest_file_count(manifest2check):
#     '''
#     Checks how many entries are in a manifest
#     '''
#     if os.path.isfile(manifest2check):
#         print(' - A manifest already exists')
#         with open(manifest2check, "r") as fo:
#             manifest_lines = [line.split(',') for line in fo.readlines()]
#             count_in_manifest = len(manifest_lines)
#     return count_in_manifest
# 
# Path: ififuncs.py
# def hashlib_manifest(manifest_dir, manifest_textfile, path_to_remove):
#     '''
#     Creates an MD5 manifest with relative filepaths.
#     '''
#     file_count = 0
#     for root, directories, filenames in os.walk(manifest_dir):
#         filenames = [f for f in filenames if not f[0] == '.']
#         directories[:] = [d for d in directories if not d[0] == '.']
#         for files in filenames:
#             #print(" - Calculating number of files to process in current directory -  %s files        \r "% file_count)
#             print("- Calculating number of files to process in current directory - {0} files ".format(file_count), end="\r")
#             file_count += 1
#     manifest_generator = ''
#     md5_counter = 1
#     for root, directories, filenames in os.walk(manifest_dir):
#         filenames = [f for f in filenames if f[0] != '.']
#         directories[:] = [d for d in directories if d[0] != '.']
#         for files in filenames:
#             print(' - Generating MD5 for %s - file %d of %d' % (os.path.join(root, files), md5_counter, file_count))
#             md5 = hashlib_md5(os.path.join(root, files))
#             md5_counter += 1
#             root2 = os.path.abspath(root).replace(path_to_remove, '')
#             try:
#                 if root2[0] == '/':
#                     root2 = root2[1:]
#                 if root2[0] == '\\':
#                     root2 = root2[1:]
#             except: IndexError
#             manifest_generator += md5[:32] + '  ' + os.path.join(root2, files).replace("\\", "/") + '\n'
#     manifest_list = manifest_generator.splitlines()
#     files_in_manifest = len(manifest_list)
#     # http://stackoverflow.com/a/31306961/2188572
#     manifest_list = sorted(manifest_list, key=lambda x: (x[34:]))
#     with open(manifest_textfile, "w", encoding='utf-8') as fo:
#         for i in manifest_list:
#             fo.write((unicodedata.normalize('NFC', i) + '\n'))
# 
# Path: ififuncs.py
# def make_desktop_logs_dir():
#     desktop_logs_dir = os.path.expanduser("~/Desktop/ifiscripts_logs")
#     if not os.path.isdir(desktop_logs_dir):
#         #I should probably ask permission here, or ask for alternative location
#         os.makedirs(desktop_logs_dir)
#     return desktop_logs_dir
# 
# def make_desktop_manifest_dir():
#     desktop_manifest_dir = os.path.expanduser("~/Desktop/moveit_manifests")
#     if not os.path.isdir(desktop_manifest_dir):
#         #I should probably ask permission here, or ask for alternative location
#         os.makedirs(desktop_manifest_dir)
#         os.makedirs(os.path.join(desktop_manifest_dir, 'old_manifests'))
#     else:
#         if not os.path.isdir(os.path.join(desktop_manifest_dir, 'old_manifests')):
#             os.makedirs(os.path.join(desktop_manifest_dir, 'old_manifests'))
#     return desktop_manifest_dir


import sys
import os
import argparse
import time
import shutil
import ififuncs
from ififuncs import generate_log
from ififuncs import manifest_file_count
from ififuncs import hashlib_manifest
from ififuncs import make_desktop_logs_dir, make_desktop_manifest_dir
        print((' %s is either not a directory or it does not exist' % source))
        generate_log(log_name_source, ' %s is either not a directory or it does not exist' % source)
        generate_log(log_name_source, 'manifest.py exit')
        sys.exit()
    remove_bad_files(source, log_name_source)
    source_count = 0
    for _, _, filenames in os.walk(source):
        # There has to be a better way to count the files..
        for _ in filenames:
            source_count += 1 #works in windows at least
    if os.path.isfile(manifest):
        count_in_manifest = manifest_file_count(manifest)
        if source_count != count_in_manifest:
            print('This manifest may be outdated as the number of files in your directory does not match the number of files in the manifest')
            generate_log(log_name_source, 'EVENT = Existing source manifest check - Failure - The number of files in the source directory is not equal to the number of files in the source manifest ')
            sys.exit()
    if not os.path.isfile(manifest):
        try:
            print('Generating source manifest')
            generate_log(log_name_source, 'EVENT = Generating source manifest')
            if args.f:
                if args.sha512:
                    ififuncs.sha512_manifest(source, manifest, source)
                else:
                    hashlib_manifest(source, manifest, source)
                shutil.move(log_name_source, source)
            else:
                if args.sha512:
                    ififuncs.sha512_manifest(source, manifest, source_parent_dir)
                else:

# Path: ififuncs.py
# def generate_log(log, what2log):
#     if not os.path.isfile(log):
#         with open(log, "w", encoding='utf-8') as fo:
#             fo.write(time.strftime("%Y-%m-%dT%H:%M:%S ")
#                      + getpass.getuser()
#                      + ' ' + what2log + ' \n')
#     else:
#         with open(log, "a", encoding='utf-8') as fo:
#             fo.write(time.strftime("%Y-%m-%dT%H:%M:%S ")
#                      + getpass.getuser()
#                      + ' ' + what2log + ' \n')
# 
# Path: ififuncs.py
# def manifest_file_count(manifest2check):
#     '''
#     Checks how many entries are in a manifest
#     '''
#     if os.path.isfile(manifest2check):
#         print(' - A manifest already exists')
#         with open(manifest2check, "r") as fo:
#             manifest_lines = [line.split(',') for line in fo.readlines()]
#             count_in_manifest = len(manifest_lines)
#     return count_in_manifest
# 
# Path: ififuncs.py
# def hashlib_manifest(manifest_dir, manifest_textfile, path_to_remove):
#     '''
#     Creates an MD5 manifest with relative filepaths.
#     '''
#     file_count = 0
#     for root, directories, filenames in os.walk(manifest_dir):
#         filenames = [f for f in filenames if not f[0] == '.']
#         directories[:] = [d for d in directories if not d[0] == '.']
#         for files in filenames:
#             #print(" - Calculating number of files to process in current directory -  %s files        \r "% file_count)
#             print("- Calculating number of files to process in current directory - {0} files ".format(file_count), end="\r")
#             file_count += 1
#     manifest_generator = ''
#     md5_counter = 1
#     for root, directories, filenames in os.walk(manifest_dir):
#         filenames = [f for f in filenames if f[0] != '.']
#         directories[:] = [d for d in directories if d[0] != '.']
#         for files in filenames:
#             print(' - Generating MD5 for %s - file %d of %d' % (os.path.join(root, files), md5_counter, file_count))
#             md5 = hashlib_md5(os.path.join(root, files))
#             md5_counter += 1
#             root2 = os.path.abspath(root).replace(path_to_remove, '')
#             try:
#                 if root2[0] == '/':
#                     root2 = root2[1:]
#                 if root2[0] == '\\':
#                     root2 = root2[1:]
#             except: IndexError
#             manifest_generator += md5[:32] + '  ' + os.path.join(root2, files).replace("\\", "/") + '\n'
#     manifest_list = manifest_generator.splitlines()
#     files_in_manifest = len(manifest_list)
#     # http://stackoverflow.com/a/31306961/2188572
#     manifest_list = sorted(manifest_list, key=lambda x: (x[34:]))
#     with open(manifest_textfile, "w", encoding='utf-8') as fo:
#         for i in manifest_list:
#             fo.write((unicodedata.normalize('NFC', i) + '\n'))
# 
# Path: ififuncs.py
# def make_desktop_logs_dir():
#     desktop_logs_dir = os.path.expanduser("~/Desktop/ifiscripts_logs")
#     if not os.path.isdir(desktop_logs_dir):
#         #I should probably ask permission here, or ask for alternative location
#         os.makedirs(desktop_logs_dir)
#     return desktop_logs_dir
# 
# def make_desktop_manifest_dir():
#     desktop_manifest_dir = os.path.expanduser("~/Desktop/moveit_manifests")
#     if not os.path.isdir(desktop_manifest_dir):
#         #I should probably ask permission here, or ask for alternative location
#         os.makedirs(desktop_manifest_dir)
#         os.makedirs(os.path.join(desktop_manifest_dir, 'old_manifests'))
#     else:
#         if not os.path.isdir(os.path.join(desktop_manifest_dir, 'old_manifests')):
#             os.makedirs(os.path.join(desktop_manifest_dir, 'old_manifests'))
#     return desktop_manifest_dir


# Path: manifest.py
import sys
import os
import argparse
import time
import shutil
import ififuncs
from ififuncs import generate_log
from ififuncs import manifest_file_count
from ififuncs import hashlib_manifest
from ififuncs import make_desktop_logs_dir, make_desktop_manifest_dir

        print((' %s is either not a directory or it does not exist' % source))
        generate_log(log_name_source, ' %s is either not a directory or it does not exist' % source)
        generate_log(log_name_source, 'manifest.py exit')
        sys.exit()
    remove_bad_files(source, log_name_source)
    source_count = 0
    for _, _, filenames in os.walk(source):
        # There has to be a better way to count the files..
        for _ in filenames:
            source_count += 1 #works in windows at least
    if os.path.isfile(manifest):
        count_in_manifest = manifest_file_count(manifest)
        if source_count != count_in_manifest:
            print('This manifest may be outdated as the number of files in your directory does not match the number of files in the manifest')
            generate_log(log_name_source, 'EVENT = Existing source manifest check - Failure - The number of files in the source directory is not equal to the number of files in the source manifest ')
            sys.exit()
    if not os.path.isfile(manifest):
        try:
            print('Generating source manifest')
            generate_log(log_name_source, 'EVENT = Generating source manifest')
            if args.f:
                if args.sha512:
                    ififuncs.sha512_manifest(source, manifest, source)
                else:
                    hashlib_manifest(source, manifest, source)
                shutil.move(log_name_source, source)
            else:
                if args.sha512:
                    ififuncs.sha512_manifest(source, manifest, source_parent_dir)
                else:

                    hashlib_manifest(source, manifest, source_parent_dir)