#!/usr/bin/env python
# authors:
# Tony Vattathil tonynv@amazon.com, avattathil@gmail.com
# Santiago Cardenas <sancard@amazon.com>, <santiago[dot]cardenas[at]outlook[dot]com>
# Shivansh Singh sshvans@amazon.com,
# Jay McConnell, jmmccon@amazon.com
"""
 Program License: Amazon License
 Python Class License: Apache 2.0
"""

from __future__ import print_function
import taskcat
import yaml
import sys
import os
import traceback
from taskcat.common_utils import exit0
from taskcat.common_utils import exit1
from taskcat.lambda_build import LambdaBuild


if sys.version_info[0] < 3:
    raise Exception("Please use Python 3")


def main():
    try:
        tcat_instance = taskcat.TaskCat()
        args = tcat_instance.interface
        tcat_instance.welcome('taskcat')
        # Initialize cli interface
        # :TODO Add RestFull Interface

        # Get configuration from command line arg (-c)
        tcat_instance.set_config(args.config_yml)
        # tcat_instance.set_config('ci/config.yml')
        # Get API Handle - Try all know auth
        tcat_instance.aws_api_init(args)
        # Optional: Enables verbose output by default (DEBUG ON)
        tcat_instance.verbose = True
    # --Begin
    # Check for valid ymal and required keys in config
        if args.config_yml is not None:

            test_list = tcat_instance.validate_yaml(args.config_yml)

    # Load yaml into local taskcat config
            with open(tcat_instance.get_config(), 'r') as cfg:
                taskcat_cfg = yaml.safe_load(cfg.read())
            cfg.close()

            # If taskcat is being executed from the project root folder, cd out and update config path
            try:
                if os.path.basename(os.path.abspath(os.path.curdir)) == taskcat_cfg['global']['qsname']:
                    config_path = tcat_instance.get_config()[2:] if tcat_instance.get_config().startswith(
                        "./") else tcat_instance.get_config()
                    os.chdir(os.path.abspath("../"))
                    tcat_instance.set_config("%s/%s" % (taskcat_cfg['global']['qsname'], config_path))
            except Exception as e:
                print(taskcat.PrintMsg.ERROR + str(e))
            project_path = '/'.join(tcat_instance.get_config().split('/')[0:-3])
            project_name = '/'.join(tcat_instance.get_config().split('/')[-3:-2])
            if "package-lambda" not in taskcat_cfg['global']:
                taskcat_cfg['global']["package-lambda"] = False
            if tcat_instance.lambda_build_only and not taskcat_cfg['global']["package-lambda"]:
                exit1("Lambda build not enabled for project. Add package-lambda: true to config.yaml global section")
            elif taskcat_cfg['global']["package-lambda"]:
                try:
                    lambda_path = os.path.abspath(project_path) + "/" + project_name + "/functions/source"
                    if os.path.isdir(lambda_path):
                        LambdaBuild(lambda_path)
                except Exception as e:
                    print("ERROR: Zipping lambda source failed: %s" % e)
                if tcat_instance.lambda_build_only:
                    exit0("Lambda source zipped successfully")
            try:
                if project_path:
                    os.chdir(os.path.abspath(project_path))
                tcat_instance.lint(args.lint, path=project_name)
            except taskcat.exceptions.TaskCatException as e:
                print(taskcat.PrintMsg.ERROR + str(e))
                exit1(str(e))
            except Exception as e:
                print("ERROR: Linting failed: %s" % e)
                if args.lint in ['error', 'strict']:
                    raise
                else:
                    traceback.print_exc()
            tcat_instance.stage_in_s3(taskcat_cfg)
            tcat_instance.validate_template(taskcat_cfg, test_list)
            tcat_instance.validate_parameters(taskcat_cfg, test_list)
            # instance.stackcreate returns testdata object
            testdata = tcat_instance.stackcreate(taskcat_cfg, test_list, args.stack_prefix)
            tcat_instance.get_stackstatus(testdata, 5)
            tcat_instance.createreport(testdata, 'index.html')
            tcat_instance.cleanup(testdata, 5)
    except taskcat.exceptions.TaskCatException as e:
        print(taskcat.PrintMsg.ERROR + str(e))
        exit1(str(e))

# --End

main()