#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2021 Tobias Koch <tobias.koch@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

import logging
import os
import sys
import textwrap

# make relocatable
INSTALL_DIR = os.path.normpath(os.path.dirname(
    os.path.realpath(sys.argv[0])) + os.sep + ".." )
sys.path.insert(1, INSTALL_DIR + os.sep + 'lib')

from aeltra.error import AeltraError
from aeltra.miscellaneous.logformatter import LogFormatter
from aeltra.osimage.cli import ImageGenCli

AELTRA_ERR_INVOCATION =  1
AELTRA_ERR_RUNTIME    =  2

LOGGER = logging.getLogger()

def print_usage():
    print(textwrap.dedent(
        """\
        Copyright (C) 2021 Tobias Koch <tobias.koch@gmail.com>

        This is the Aeltra OS image generator tool.

        USAGE:

          aeltra-image [OPTIONS] <command> [ARGS]

        COMMANDS:

          bootstrap        Bootstrap a system into a chroot.
          customize        Apply additional customizations.
          cleanup          Clean up chroot before packaging.
          package          Create an image for distribution.

        OPTIONS:

          -h, --help       Print this help messsage.

        Type `aeltra-image <command> --help` for more information about
        individual commands.\
        """
    ))
#end function

def configure_logging():
    fmt = LogFormatter("aeltra-image")
    handler = logging.StreamHandler()
    handler.setFormatter(fmt)
    LOGGER.addHandler(handler)
    LOGGER.setLevel(logging.INFO)
#end function

if __name__ == "__main__":
    try:
        configure_logging()

        if len(sys.argv) < 2:
            print_usage()
            sys.exit(AELTRA_ERR_INVOCATION)

        command = sys.argv[1]

        if command in ["bootstrap", "customize", "cleanup", "package"]:
            ImageGenCli().execute_command(*sys.argv[1:])
        elif command in ["--help", "-h"]:
            print_usage()
        else:
            LOGGER.error('unknown command "{}".'.format(command))
            sys.exit(AELTRA_ERR_INVOCATION)
        #end if
    except AeltraError as e:
        LOGGER.error(e)
        sys.exit(AELTRA_ERR_RUNTIME)
    except KeyboardInterrupt:
        LOGGER.warning("caught keyboard interrupt, exiting.")
        sys.exit(AELTRA_ERR_RUNTIME)
    #end try
#end __main__
