#!/usr/bin/env python3
import logging
import os
import sys

from edbdeploy import cli
from edbdeploy import command
from edbdeploy.errors import (
	AnsibleCliError,
	CliError,
	CloudCliError,
	ProjectError,
	SpecValidatorError,
	TerraformCliError,
)
from edbdeploy.project import Project

def configure_project_logging(project, sub_command):

    project.create_log_dir()

    logging.basicConfig(
        filename=project.log_file,
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)7s '+sub_command+': %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
    )

def configure_root_logging(cloud, sub_command):
    # Configure logging module for the sub-commands that do not take project
    # name argument.
    Project.create_root_log_dir()

    logging.basicConfig(
        filename=os.path.join(
            Project.projects_root_path, "log", "%s_%s.log" % (cloud, sub_command)
        ),
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)7s '+sub_command+': %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
    )


if __name__ == "__main__":

    try:

        # Parse the commande line
        env = cli.parse()

        # Create a new Commander in charge of executing the sub-command
        commander = command.Commander(env)

        # Configure logging
        if commander.project:
            configure_project_logging(commander.project, env.sub_command)
        else:
            configure_root_logging(env.cloud, env.sub_command)

        logging.debug("env=%s", env)

        # Execute the sub-command
        commander.execute()

    except (
        command.CommanderError,
        CliError,
        CloudCliError,
        ProjectError,
        TerraformCliError,
        AnsibleCliError,
        SpecValidatorError
    ) as e:
        # Update states
        if isinstance(e, TerraformCliError):
            commander.project.update_state('terraform', 'FAIL')
        if isinstance(e, AnsibleCliError):
            commander.project.update_state('ansible', 'FAIL')

        sys.stderr.write("ERROR: %s\n" % str(e))
        sys.exit(2)
    except KeyboardInterrupt as e:
        sys.exit(1)
    except Exception as e:
        # Unhandled error
        sys.stderr.write("ERROR: %s\n" % str(e))
        logging.exception(str(e))
        sys.exit(2)
