#!/usr/bin/env python
from optparse import OptionParser
import sys
import traceback
from jtalks.ApplicationContext import ApplicationContext
from jtalks.DeployToTomcatFacade import DeployToTomcatFacade
from jtalks.util.LibVersion import LibVersion
from jtalks.util.Logger import Logger

__author__ = 'stanislav bashkirtsev'

"""
  This script downloads the artifact from Nexus (only project name and build number is enough because it's unique)
  and deploys the artifact to the Tomcat. 
  
  Run: python [scriptname].py -h to get list of options.
"""
logger = Logger("entry-point")


def main():
  (options, args) = get_project_and_build_from_arguments()
  command = args[0]
  app_context = ApplicationContext(options.env, options.project, options.build)
  try:
    if command == "deploy":
      LibVersion().log_lib_versions()
      DeployToTomcatFacade().deploy(options.build, options.project, options.env)
    elif command == "upload-to-nexus":
      LibVersion().log_lib_versions()
      app_context.nexus().upload_war("pom.xml")
    elif command == "list-envs":
      app_context.env_list().list_envs()
    elif command == "load-db-from-backup":
      app_context.load_db_from_backup().load()
    else:
      logger.error("Command was not recognized, you can use: [deploy], [upload-to-nexus]")
      raise RuntimeError
  except Exception:
    logger.error("Program finished with errors")
    if options.debug:
      print traceback.format_exc()
      logger.error("Root cause: %s" % traceback.format_exc())
    sys.exit(1)


def get_project_and_build_from_arguments():
  """
  Gets the build number from parameters passed to the script (the -b or --build options). 
  If nothing was specified, None is returned.
  """
  parser = OptionParser()
  parser.add_option("-b", "--build", dest="build",
                    help="The build number of the Deployment Pipline to deploy a unique artifact to Nexus.")
  parser.add_option("-p", "--project", dest="project",
                    help="Project name to be deployed to tomcat (e.g. jcommune, poulpe)")
  parser.add_option("-e", "--environment", dest="env",
                    help="Environment to be deployed. Environment MUST exist on current server. Run [list-envs] to "
                         "see possible values")
  parser.add_option("-d", "--debug", dest="debug",
                    help="Whether to show additional errors and logs or not")
  (options, args) = parser.parse_args()
  if len(args) == 0:
    logger.error("No command was specified, you can use: [install], [upload-to-nexus]")
  return (options, args)

"""Starting the script by invoking main() method """
if __name__ == "__main__":
  main()
