#!/usr/bin/python3
#
# composer-cli
#
# Copyright (C) 2018  Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
import logging
log = logging.getLogger("composer-cli")

import os
import sys

from composer import vernum
from composer.cli import main
from composer.cli.cmdline import composer_cli_parser

VERSION = "{0}-{1}".format(os.path.basename(sys.argv[0]), vernum)

def setup_logging(logfile=None):
    """ Setup logging to console and to an optional logfile

    :param logfile: Optional path to file to store logs in
    :type logfile: None or str
    """
    log.setLevel(logging.DEBUG)

    sh = logging.StreamHandler()
    sh.setLevel(logging.INFO)
    fmt = logging.Formatter("%(asctime)s: %(message)s")
    sh.setFormatter(fmt)
    log.addHandler(sh)

    if logfile != None:
        fh = logging.FileHandler(filename=logfile)
        fh.setLevel(logging.DEBUG)
        fmt = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
        fh.setFormatter(fmt)
        log.addHandler(fh)

if __name__ == '__main__':
    # parse the arguments
    arg_parser = composer_cli_parser()
    opts = arg_parser.parse_args()

    if opts.showver:
        print(VERSION)
        sys.exit(0)

    if opts.logfile != None:
        logpath = os.path.abspath(os.path.dirname(opts.logfile))
        if not os.path.isdir(logpath):
            os.makedirs(logpath)
    setup_logging(opts.logfile)
    log.debug("opts=%s", opts)

    if len(opts.args) == 0:
        log.error("Missing command")
        sys.exit(1)
    elif opts.args[0] == "help":
        arg_parser.print_help()
        sys.exit(0)
    elif len(opts.args) == 1:
        log.error("Missing %s sub-command", opts.args[0])
        sys.exit(1)

    errors = []

    # Check to see if the socket exists and can be accessed
    if not os.path.exists(opts.socket):
        errors.append("%s does not exist" % opts.socket)
    elif not os.access(opts.socket, os.R_OK|os.W_OK):
        errors.append("This user cannot access %s" % opts.socket)

    # No point in continuing if there are errors
    if errors:
        for e in errors:
            log.error(e)
        sys.exit(1)

    sys.exit(main(opts))
