#!/usr/bin/env python3

import os
import os.path
import sys

"""
# For all files in a directory, create ACEDB file
# objects in ace flatfile format. Ignore symbolic links
# Write output to the target directory, in a file called datfiles.ace.
"""

""" ensure that there are enough command line arguments to parse """
if len(sys.argv) < 2:
    print("Missing PATH parameter");
    print("");
    print("Usage: dat2ace.py  PATH");
    exit();

#----------- File paths -----------------------------------
# Get the path to the target directory and the value of $BIRCH
path = sys.argv[1]
print 'path= ' + path
full_path = os.path.normpath(os.path.expanduser(os.path.expandvars(path)))
print 'full_path= ' + full_path

birch_path=os.environ.get('BIRCH')

# dir_string is the name that we write to the output file. 
# If the path begins with the value of $BIRCH, we substitute '$BIRCH',
# so that the name of the environment variable appears in the database
dir_string=""
if full_path.startswith(birch_path):
   dir_string = full_path.replace(birch_path,'$BIRCH',1)   
print 'dir_string= ' + dir_string

outlocation = os.path.expandvars(os.path.join(full_path, 'datfiles.ace'))
print 'outlocation= ' + outlocation

#------------------ Main procedure -----------------------------------------
if os.path.exists(full_path) and os.path.isdir(full_path):
    aceout = open(outlocation, 'w')
    print 'dat2ace.py: Writing output to ' + outlocation
    for file in os.listdir(full_path):
        if not file == 'datfiles.ace' :
           file_path = os.path.join(full_path, file)
           if os.path.isfile(file_path): 
	       # .ace syntax requires that all '/' characters be escaped
               FN = os.path.join(dir_string, file).replace('/', '\\/')
               aceout.write('File : "' + FN + '"\n')
               aceout.write('Pick_me_to_call "$ACE_FILE_LAUNCHER" "' + FN + '"\n')
               aceout.write('\n')
    aceout.close()
else:
    print 'dat2ace.py: Directory ' + full_path + ' not found.'
