#!/usr/bin/python
# @package      hubzero-submit-client
# @file         submit
# @author       Steven Clark <clarks@purdue.edu>
# @copyright    Copyright (c) 2012 HUBzero Foundation, LLC.
# @license      http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
#
# Copyright (c) 2012 HUBzero Foundation, LLC.
#
# This file is part of: The HUBzero(R) Platform for Scientific Collaboration
#
# The HUBzero(R) Platform for Scientific Collaboration (HUBzero) is free
# software: you can redistribute it and/or modify it under the terms of
# the GNU Lesser General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# HUBzero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#
import os
import sys
import subprocess

LOGDIRECTORY = os.getcwd()
HUBLOGFILE   = '.submit.log'

CONFIGURATIONDIRECTORY = os.path.join(os.sep,'etc','submit')
CONFIGURATIONFILE      = 'submit-client.conf'
CONFIGFILEPATH         = os.path.join(CONFIGURATIONDIRECTORY,CONFIGURATIONFILE)

DEFAULTPEGASUSVERSION = "4.0.0"

def setupPegasus():
   pegasusVersion    = None
   pegasusHome       = None
   pegasusPythonPath = None
   
   try:
      from Pegasus.DAX3 import ADAG

      pegasusCommand = ['pegasus-version']
      child = subprocess.Popen(pegasusCommand,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)
      pegasusStdOutput,pegasusStdError = child.communicate()
      pegasusExitStatus = child.returncode
      if pegasusExitStatus == 0:
         pegasusVersion = pegasusStdOutput.strip()

         pegasusCommand = ['pegasus-config','--bin']
         child = subprocess.Popen(pegasusCommand,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE,
                                  close_fds=True)
         pegasusStdOutput,pegasusStdError = child.communicate()
         pegasusExitStatus = child.returncode
         if pegasusExitStatus == 0:
            pegasusHome = os.path.dirname(pegasusStdOutput.strip())

            pegasusCommand = ['pegasus-config','--python']
            child = subprocess.Popen(pegasusCommand,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE,
                                     close_fds=True)
            pegasusStdOutput,pegasusStdError = child.communicate()
            pegasusExitStatus = child.returncode
            if pegasusExitStatus == 0:
               pegasusPythonPath = pegasusStdOutput.strip()
   except:
      pass
   
   if not pegasusVersion or not pegasusHome or not pegasusPythonPath:
      pegasusCommand = ". /etc/environ.sh\n" + \
                       "use -e -r pegasus-%s\n" % (DEFAULTPEGASUSVERSION) + \
                       "pegasus-version\n" + \
                       "pegasus-config --bin\n" + \
                       "pegasus-config --python"
      child = subprocess.Popen(pegasusCommand,shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)
      pegasusStdOutput,pegasusStdError = child.communicate()
      pegasusExitStatus = child.returncode
      if pegasusExitStatus == 0:
         try:
            pegasusVersion,pegasusBin,pegasusPythonPath = pegasusStdOutput.strip().split()
            pegasusHome = os.path.dirname(pegasusBin)
            if not pegasusPythonPath in sys.path:
               sys.path.insert(0,pegasusPythonPath)
               from Pegasus.DAX3 import ADAG
         except:
            pegasusVersion    = ""
            pegasusHome       = ""
            pegasusPythonPath = ""
   
   return(pegasusVersion,pegasusHome)

PEGASUSVERSION,PEGASUSHOME = setupPegasus()

from hubzero.submit.LogMessage   import openLog, logID as log, logSetMessageFile
from hubzero.submit.SubmitClient import SubmitClient

def openLogFile(logDirectory,
                hubLogFile):
   if sys.stderr.isatty():
      logSetMessageFile(sys.stderr)
   else:
      hubLogPath = os.path.join(logDirectory,hubLogFile)
      openLog(hubLogPath)


def client(configFilePath,
           pegasusVersion,
           pegasusHome):
   if pegasusVersion and pegasusHome:
      submitClient = SubmitClient(pegasusVersion,pegasusHome)

      if submitClient.configure(configFilePath):
         if submitClient.parseCommandArguments():
            if not submitClient.reportDebugOutput():
               logSetMessageFile(None)
            if submitClient.haveIdAuthAttributes():
               if submitClient.connect():
                  submitClient.sendContext()
                  submitClient.signon()
                  submitClient.run()
               else:
                  log("Connection to submit server failed.")
            else:
               log("Could not acquire proper authentication information")
      else:
         log("submit configuration failed.")
         sys.exit(1)
   else:
      log("unable to determine pegasus version.")
      sys.exit(1)


if __name__ == '__main__':
   openLogFile(LOGDIRECTORY,HUBLOGFILE)

   client(CONFIGFILEPATH,PEGASUSVERSION,PEGASUSHOME)

   sys.exit(0)
