#!/usr/bin/env python
from optparse import OptionParser
import sys

from jtalks.Main import Main
from jtalks.util.Logger import Logger


"""
  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. It expects the configuration of the app being placed into
  `~/.jtalks/environments`.

  Run: python [scriptname].py -h to get list of options.
"""
logger = Logger("entry-point")


def main():
    (options, args) = get_project_and_build_from_arguments()
    logger.info("Script Params: {0}", options)
    Main().main(args, options)


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 Pipeline 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). Script looks up the app
                      configs in `~/.jtalks/environments` by this name.''')
    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('-g', '--grab-envs', dest="grab_envs", default="false",
                      help='''Whether or not to clone configs from JTalks Git repository,
                      requires appropriate SSH access allowed. Possible values - true and false.
                      False by default''')
    parser.add_option('-t', '--sanity-test-timeout-sec', dest='sanity_test_timeout_sec', default=120,
                      help='''After the app is deployed, scripts check whether it was deployed successfully by sending
                      an HTTP request. This argument says for how long to wait before we consider the
                      deployment failed.''')
    parser.add_option('-d', '--debug', dest='debug', default='off',
                      help='Whether to show additional errors and logs or not. Possible values: on/off.')
    (options, args) = parser.parse_args()
    if len(args) == 0:
        logger.error("No command was specified, you can use: [deploy], [upload-to-nexus]")
        sys.exit(1)
    return options, args


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