#!/usr/bin/env python3
#
# Copyright BitBake Contributors
#
# SPDX-License-Identifier: GPL-2.0-only
#

import os
import sys,logging
import argparse
import warnings
warnings.simplefilter("default")

sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), "lib"))

import prserv
import prserv.serv

VERSION = "2.0.0"

PRHOST_DEFAULT="0.0.0.0"
PRPORT_DEFAULT=8585

def init_logger(logfile, loglevel):
    numeric_level = getattr(logging, loglevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError("Invalid log level: %s" % loglevel)
    FORMAT = "%(asctime)-15s %(message)s"
    logging.basicConfig(level=numeric_level, filename=logfile, format=FORMAT)

def main():
    parser = argparse.ArgumentParser(
        description="BitBake PR Server. Version=%s" % VERSION,
        formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument(
        "-f",
        "--file",
        default="prserv.sqlite3",
        help="database filename (default: prserv.sqlite3)",
    )
    parser.add_argument(
        "-l",
        "--log",
        default="prserv.log",
        help="log filename(default: prserv.log)",
    )
    parser.add_argument(
        "--loglevel",
        default="INFO",
        help="logging level, i.e. CRITICAL, ERROR, WARNING, INFO, DEBUG",
    )
    parser.add_argument(
        "--start",
        action="store_true",
        help="start daemon",
    )
    parser.add_argument(
        "--stop",
        action="store_true",
        help="stop daemon",
    )
    parser.add_argument(
        "--host",
        help="ip address to bind",
        default=PRHOST_DEFAULT,
    )
    parser.add_argument(
        "--port",
        type=int,
        default=PRPORT_DEFAULT,
        help="port number (default: 8585)",
    )
    parser.add_argument(
        "-r",
        "--read-only",
        action="store_true",
        help="open database in read-only mode",
    )
    parser.add_argument(
        "-u",
        "--upstream",
        default=os.environ.get("PRSERV_UPSTREAM", None),
        help="Upstream PR service (host:port)",
    )

    args = parser.parse_args()
    init_logger(os.path.abspath(args.log), args.loglevel)

    if args.start:
        ret=prserv.serv.start_daemon(
            args.file,
            args.host,
            args.port,
            os.path.abspath(args.log),
            args.read_only,
            args.upstream
        )
    elif args.stop:
        ret=prserv.serv.stop_daemon(args.host, args.port)
    else:
        ret=parser.print_help()
    return ret

if __name__ == "__main__":
    try:
        ret = main()
    except Exception:
        ret = 1
        import traceback
        traceback.print_exc()
    sys.exit(ret)

