#!/usr/bin/env python3

import os
import os.path
import sys

"""
# For all documentation files in a directory, create ACEDB file
# objects in ace flatfile format. Ignore symbolic links
# Documentation files are identified by common file extensions, 
# listed in file_ext_list.
# Write output to the target directory, in a file called docfiles.ace.
"""

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

#------------------ Main procedure -----------------------------------------
file_ext_list = ['.pdf', '.ps', '.doc', '.docx', '.txt', '.asc', '.html', '.htm', '.man', '.sxw', '.sxc', '.sxi', '.odt', '.rst', '.help']
if os.path.exists(full_path) and os.path.isdir(full_path):
    aceout = open(outlocation, 'w')
    print('doc2ace.py: Writing output to ' + outlocation)
    for file in os.listdir(full_path):
        if (not file == 'docfiles.ace') and (str(os.path.splitext(file)[1]).lower() in file_ext_list) :
           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('doc2ace.py: Directory ' + full_path + ' not found.')
