#!python

from mycotools.lib.kontools import format_path
from mycotools.lib.dbtools import masterDB
import sys, datetime, os, re

if __name__ == '__main__':

    description = 'MycotoolsDB utility' + \
        '\n\nDEFAULT: print MycotoolsDB file path and exit' + \
        '\n[-i DBPATH]\t[--init DBPATH]\tAdd MycotoolsDB to PATH and initialize'
    set_argv = set(sys.argv)
    if '-h' in set_argv or '--help' in set_argv:
        print('\n' + description + '\n', flush = True)
        sys.exit(0)
    if '-i' in set_argv or '--init' in set_argv:
        if '-i' in set_argv:
            coord = '-i'
        else:
            coord = '--init'
        mycodb_loc = format_path(sys.argv[sys.argv.index(coord) + 1])
        if not os.path.isdir(mycodb_loc + 'mycodb'):
            print('\nERROR: invalid mycotoolsdb path.', flush = True)
            sys.exit(1)
        else:
            dPath = mycodb_loc + 'data/'
            updateData = '## MYCOTOOLSDB' + \
                '\nexport MYCODB=' + mycodb_loc + 'mycodb/' + \
                '\nexport MYCOFNA=' + dPath + 'fna' + \
                '\nexport MYCOFAA=' + dPath + 'faa' + \
                '\nexport MYCOGFF3=' + dPath + 'gff3' + \
                '\n## END MYCOTOOLSDB'
            if 'MYCODB' in os.environ:
                print('\nERROR: mycotoolsdb already in path', flush = True)
                sys.exit(2)
            with open(format_path('$HOME/.bash_profile'), 'a') as raw:
                raw.write('\n' + updateData)
            print('\nMycotoolsDB added to path. Restart shell/environment to finish\n', flush = True)
            os.environ['MYCODB'] = mycodb_loc + 'mycodb/'


    path = masterDB()
    if path:
        print( path )
        sys.exit( 0 )
    else:
        sys.exit(1)
