#!/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.tsv.
"""

""" ensure that there are enough command line arguments to parse """
if len(sys.argv) < 2:
    print("Missing PATH parameter");
    print("");
    print("Usage: dat2birchdb.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.tsv'))
print('outlocation= ' + outlocation)

#------------------ Main procedure -----------------------------------------
if os.path.exists(full_path) and os.path.isdir(full_path):
    outfile = open(outlocation, 'w')
    print('dat2birchdb.py: Writing output to ' + outlocation)
    NL = "\n"
    SEPLINE = "--------------------------------" + NL
    TAB = "\t"
    SEMI = ";"
    for file in os.listdir(full_path):
        if not file == 'datfiles.tsv' :
           file_path = os.path.join(full_path, file)
           if os.path.isfile(file_path): 
               outfile.write(SEPLINE)
               FN = os.path.join(dir_string, file)
               outfile.write("INSERT_INTO " + TAB + " FILE " + TAB + FN + NL)
               outfile.write("Description " + TAB + "datafile" + NL)
               outfile.write("Command" + TAB + "$ACE_FILE_LAUNCHER" + TAB + FN + NL)
               outfile.write(SEMI + NL)
    outfile.close()
else:
    print('dat2birchdb.py: Directory ' + full_path + ' not found.')
