#! /usr/bin/python3
# -*- encoding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2020 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 os
import sys
import getopt
import logging
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.distro.config.cli import (
    Cli as DistroInfoCli, EXIT_OK, EXIT_ERROR
)
from aeltra.distro.config.error import DistroInfoError
from aeltra.miscellaneous.logformatter import LogFormatter

LOGGER = logging.getLogger()

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

        This is a command line utility for retrieving and printing information about
        Aeltra OS releases and available mirrors.

        USAGE:

          aeltra-distro-info [OPTIONS] <command> <args>

        COMMANDS:

          refresh              Update the releases and mirrors lists.
          list                 List releases.
          show                 Show information about a given release.

        OPTIONS:

          -h, --help           Print this help message.
          --api-version VER    API version (default: 1)

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

def parse_cmd_line():
    # define default configuration
    config = {
        "api_version": 1
    }

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "api-version="])
    except getopt.GetoptError as e:
        raise DistroInfoError("error parsing command line: {}".format(str(e)))

    for o, v in opts:
        if o in ["--help", "-h"]:
            print_usage()
            sys.exit(EXIT_OK)
        elif o == "--api-version":
            try:
                config["api_version"] = int(v)
            except ValueError as e:
                raise DistroInfoError(
                    "invalid API version: {}".format(str(e))
                )
            #end try
        #end if
    #end for

    return config, args
#end function

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

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

        options, args = parse_cmd_line()

        if len(args) < 1:
            print_usage()
            sys.exit(EXIT_ERROR)

        command = args.pop(0)

        di = DistroInfoCli(options)

        if not hasattr(di, command):
            print_usage()
            sys.exit(EXIT_ERROR)

        getattr(di, command)(*args)
    except DistroInfoError as e:
        LOGGER.error(e)
        sys.exit(EXIT_ERROR)
    except KeyboardInterrupt:
        LOGGER.warning("caught keyboard interrupt, exiting.")
        sys.exit(EXIT_ERROR)
    #end try
#end __main__
