#!/usr/bin/env python3

#optparse is deprecated in favor of argparse as of Python 2.7. However,
# since 2.7 is not always present on many systems, at this writing,
# it is safer to stick with optparse for now. It should be easy
# to change later, since the syntax is very similar between argparse and optparse.
from optparse import OptionParser

import os
import os.path
import stat
import subprocess
import sys
import re
import shutil


'''
BIRCHUserSettings.py - Set environment variables for BioLegato Helper Applications

Synopsis: BIRCHUserSettings.py --setvar variable_name=value

@modified: July  5, 2020
@author: Brian Fristensky
@contact: frist@cc.umanitoba.ca
'''

blib = os.environ.get("BIRCHPYLIB")
HOMEDIR = os.environ.get("HOME")

sys.path.append(blib)

from birchlib import Birchmod


PROGRAM = "BIRCHUserSettings.py : "
USAGE = "\n\t\tBIRCHUserSettings.py --setvar variable_name=value"

DEBUG = True
if DEBUG :
    print('Debugging mode on')

BM = Birchmod(PROGRAM, USAGE)

BIRCHvariables = ["BIRCH_PROMPT","BL_EMAIL","NCBI_ENTREZ_KEY"]

# - - - - - - - - - - - - - Utility classes - - - - - - - - - - - - - - - - -
def chmod_rw(filename):
    if os.path.exists(filename):
        st = os.stat(filename)
        os.chmod(filename, stat.S_IRUSR | stat.S_IWUSR)

def chmod_rwx(filename):
    if os.path.exists(filename):
        st = os.stat(filename)
        os.chmod(filename, stat.S_IRWXU)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Parameters:
    """
        Wrapper class for command line parameters
        """
    def __init__(self):
        """
          Initializes arguments:
                SETVAR = False
                VSTRING = ""
                VNAME   = ""
                VALUE   = ""
                SFN= ""


          Then calls read_args() to fill in their values from command line
          """
        self.SETVAR  = False
        self.VSTRING = ""
        self.VNAME   = ""
        self.VALUE   = ""
        self.read_args()
        self.SFN = os.path.join(HOMEDIR , '.config' , 'BIRCH' , 'BIRCHsettings.source')

        if DEBUG :
            print('------------ Parameters from command line ------')
            print('    SETVAR: ' + str(self.SETVAR))
            print('    VNAME: ' + self.VNAME)
            print('    VALUE: ' + self.VALUE)
            print('    Settings file: ' + self.SFN)
            print()

    def read_args(self):
        """
                Read command line arguments into a Parameter object
        """

        parser = OptionParser()
        parser.add_option("--setvar", dest="vstring", action="store", default="",
                          help="set an environment variable to the specified value")
        (options, args) = parser.parse_args()
        self.VSTRING = options.vstring
        if self.VSTRING != "" :
            self.SETVAR = True
            tokens = self.VSTRING.split("=")
            self.VNAME = tokens[0]
            self.VALUE = tokens[1]

# - - - - - - - - - -  Make sure that the user's config directory exists - - - - - -
def CheckConfigDir():
    OKAY=True
    configpath=os.path.join(HOMEDIR,".config")
    configBIRCHpath=os.path.join(HOMEDIR,".config","BIRCH")
    #try :
    if not os.path.exists(configpath) :
        os.mkdir(configpath)
        chmod_rwx(configBIRCHpath)
    if not os.path.exists(configBIRCHpath) :
        os.mkdir(configBIRCHpath)
        chmod_rwx(configBIRCHpath)
    #except :
    #    print("BIRCHUserSettings.py: Couldn't create " + configBIRCHpath)
    #    OKAY = False
    return OKAY 


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class BIRCHUserSettings:
    """
        Data and methods for the BIRCH Settings file.
        """
    def __init__(self,P):
        """
          Initializes arguments:
                dict = {}
          """
        self.dict = {}
        for var in BIRCHvariables:
            self.dict[var] = ""

        if os.path.exists(P.SFN) :
            self.ReadBIRCHUserSettings(P.SFN)
        #else:
        #    DFN = os.path.join(self.BIRCH , 'admin' , 'BIRCH.settings.default')
        #    self.ReadBIRCHUserSettings(DFN)

        if DEBUG :
            print('- - - - - BIRCH Settings - - - - -')
            for k in self.dict :
                print('    ' + k + ',' + self.dict[k])

    def ReadBIRCHUserSettings(self,FN):
        """
                Read current values of BIRCHvariables from BIRCH.settings.
        """

        if os.path.exists(FN) :
            Sfile = open(FN,'r')
            for line in Sfile :
                line = line.strip()
                # ignore blank lines and comment lines
                if (line != "" and line[0] != '#') :
                    print(line)
                    tokens = line.split("=")
                    if tokens[0] in BIRCHvariables :
                        self.dict[tokens[0]] = tokens[1]
            Sfile.close()


    def WriteBIRCHUserSettings(self,SFN):
        """
                Write current values of BIRCHvariables to $HOME/.config/BIRCH/BIRCHsettings.source file.
        """

        Sfile = open(SFN,'w')
        Sfile.write('#!/bin/bash\n')
        Sfile.write('# DO NOT EDIT THIS FILE!\n')
        Sfile.write('# This file is automatically generated by BIRCHUserSettings.py \n')
        # Write a bash statement setting each variable. Build an export line as we go
        # Because these parameters are designed to override system parametera,
        # we only write those variables that are non-blank.
        ExLine = "export "
        for k in self.dict :
            if not self.dict[k] == "" :
                Sfile.write(k + '=' + self.dict[k] + '\n')
                ExLine = ExLine + " " + k
        # Write a bash statement exporting each variable to the shell
        Sfile.write(ExLine)
        Sfile.write("\n")
        Sfile.close()
        os.chmod(SFN, 0o700)


#======================== MAIN PROCEDURE ==========================
def main():
    """
        Called when not in documentation mode.
        """

    # Read parameters from command line
    P = Parameters()

    if CheckConfigDir() :

        Settings = BIRCHUserSettings(P)

        if P.SETVAR:
            print("Setvar")
            if P.VNAME in BIRCHvariables:
                Settings.dict[P.VNAME] = P.VALUE
                Settings.WriteBIRCHUserSettings(P.SFN)
    else:
        print(USAGE)

    BM.exit_success()


if (BM.documentor() or "-test" in sys.argv):
    pass
else:
    main()
