#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2017-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 build-box 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.buildbox.cli import BuildBoxCLI
from aeltra.buildbox.error import BuildBoxError
from aeltra.error import AeltraError
from aeltra.miscellaneous.logformatter import LogFormatter

BUILD_BOX_ERR_INVOCATION = 1
BUILD_BOX_ERR_RUNTIME    = 2

LOGGER = logging.getLogger()

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

        This is the Build Box NG management utility.

        USAGE:

          build-box [OPTIONS] <command> [ARGS]

        COMMANDS:

          create        Create new target.
          delete        Remove a target.
          info          Print information about a target.
          list          List all existing targets.
          login         Chroot into a target.
          mount         Mount homedir and special file systems (dev, proc, sys).
          umount        Unmount homedir and special file systems.
          run           Execute a command chrooted inside a target.

        OPTIONS:

          -h, --help    Print this help message and exit.

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

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

if __name__ == "__main__":
    os.environ["BUILD_BOX_WRAPPER_A883DAFC"] = "1"

    try:
        log_formatter = configure_logging()
        if os.getuid() == 0:
            raise BuildBoxError("build-box must not be used by root")

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

        command = sys.argv[1]

        sys.stdout.flush()
        sys.stderr.flush()

        if command in ["init", "login", "mount", "umount", "run"]:
            try:
                os.execvp("build-box-do", sys.argv[:])
            except OSError as e:
                raise BuildBoxError(
                    "failed to exec build-box-do: {}".format(str(e))
                )
        elif command in ["create", "info", "list", "delete"]:
            log_formatter.set_app_name(
                "build-box {}".format(command)
            )
            BuildBoxCLI().execute_command(*sys.argv[1:])
        elif command in ["--help", "-h"]:
            print_usage()
        else:
            LOGGER.error('unknown command "{}".'.format(command))
            sys.exit(BUILD_BOX_ERR_INVOCATION)
        #end if
    except AeltraError as e:
        LOGGER.error(e)
        sys.exit(BUILD_BOX_ERR_RUNTIME)
    except KeyboardInterrupt:
        LOGGER.warning("caught keyboard interrupt, exiting.")
        sys.exit(0)
    #end try
#end __main__
