#! /usr/bin/env python3

import os
from optparse import OptionParser

# Copied from qmca. Modification must done on qmca first
# Locate and import the closely coupled Nexus module
def find_nexus_modules():
    import os
    import sys
    # Prepend the assumed path of a folder containing the closely coupled nexus module to module search path
    # It points to the top Nexus directory not necessarily the top QMCPACK directory.
    nexus_lib = os.path.realpath(os.path.join(__file__,'..','..'))

    # "import nexus" will succeed if nexus directory exists without __init__.py in it.
    # Explicitly check the existence of nexus/__init__.py at the closely coupled location
    nexus_init = os.path.join(nexus_lib,'nexus','__init__.py')
    if not os.path.exists(nexus_init):
        print('\nExpected file '+nexus_init+' does not exist!'
              '\nBroken Nexus installation! Please follow Nexus manual regarding installation.\n')
        sys.exit(1)

    # check import of nexus modules
    sys.path.insert(0,nexus_lib)
    try:
        import nexus
    except Exception as err:
        print('\nImporting Nexus modules failed for an unknown reason.'
              '\nThis is likely a developer error.'
              '\nFor more information, the original exception is reproduced below.'
              '\nPlease report this error to the Nexus developers.'+2*'\n')
        import traceback
        exc_type, exc_value, exc_traceback = sys.exc_info()
        exc_lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        for line in exc_lines:
            print(line.rstrip())
        print()
        sys.exit(1)

    # Sanity check. Most likely errors get caught earlier.
    # ensure closely coupled nexus module is in use.
    nexus_lib2 = os.path.realpath(os.path.join(nexus.__file__,'..','..'))
    if nexus_lib != nexus_lib2:
        exe_full_path = os.path.abspath(sys.argv[0])
        print('\nNexus executable ' + exe_full_path +
              '\n  Executable derived <nexus_root> = ' + nexus_lib +
              '\n  Module     derived <nexus_root> = ' + nexus_lib2 +
              '\nNexus executables and modules are not from the same installation!\n')
        sys.exit(1)
#end def find_nexus_modules

# Get Nexus version
find_nexus_modules()
from nexus.nexus_version import nexus_version


usage  = '''usage: %prog [options] [file(s)]'''
parser = OptionParser(usage=usage,add_help_option=False,version='%prog {}.{}.{}'.format(*nexus_version))
parser.add_option('-h','--help',dest='help',
                  action='store_true',default=False,
                  help='Print help information and exit (default=%default).'
                  )
parser.add_option('-v','--verbose',dest='verbose',
                          action='store_true',default=False,
                          help='Print detailed information (default=%default).'
                          )
parser.add_option('-n','--dry-run',dest='dryrun',
                  action='store_true',default=False,
                  help="Print directories to be backed up as previous attempts, but don't actually do anything (default=%default)."
                  )

options,paths_in = parser.parse_args()

help    = options.__dict__['help']
verbose = options.__dict__['verbose']
dryrun  = options.__dict__['dryrun']

if help:
    print(parser.format_help())
    exit()
#end if

paths = dict()
if len(paths_in)==1 and os.path.exists(paths_in[0]) and os.path.isfile(paths_in[0]):
    text = open(paths_in[0],'r').read()
    paths_in = []
    for line in text.splitlines():
        tokens = line.split()
        if len(tokens)>0:
            paths_in.append(tokens[-1])
        #end if
    #end for
#end if
for path in paths_in:
    if os.path.exists(path) and os.path.isdir(path):
        simdir    = False
        attempts  = []
        contents  = []
        for item in os.listdir(path):
            isdir = os.path.isdir(os.path.join(path,item))
            simdir |= item.startswith('sim') and isdir
            if item.startswith('attempt') and isdir:
                attempts.append(item)
            else:
                contents.append(item)
            #end if
        #end for
        if simdir:
            paths[path] = attempts,contents
        #end if
    #end if
#end for

if len(paths)>0:
    if verbose:
        print('redo: backing up attempted sim runs')
    #end if
else:
    print('redo: no simulation directories found')
    exit()
#end if
cwd = os.getcwd()
for path in sorted(paths.keys()):
    if verbose:
        print('  Entering '+path)
    #end if
    os.chdir(path)
    attempts,contents = paths[path]
    attempt_dir = 'attempt'+str(len(attempts)+1)
    if verbose:
        if len(contents)==0:
            print('    no contents to backup')
        elif dryrun:
            print('    would have created backup of {0} files in directory {1}'.format(len(contents),attempt_dir))
        else:
            print('    creating backup of {0} files in directory {1}'.format(len(contents),attempt_dir))
        #end if
    #end if
    if not dryrun and len(contents)>0:
        os.mkdir(attempt_dir)
        if os.path.exists(attempt_dir) and os.path.isdir(attempt_dir):
            for item in contents:
                os.system('mv {0} {1}'.format(item,attempt_dir))
            #end for
        else:
            print('  failed to create backup directory '+os.path.join(path,attempt_dir))
        #end if
    #end if
    os.chdir(cwd)
#end for

if verbose:
    print('redo: backup complete')
#end if
