#!/usr/bin/python3
#
# Copyright (C) 2010-2011, Benjamin Drung <bdrung@ubuntu.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# pylint: disable=invalid-name
# pylint: enable=invalid-name

import argparse
import logging
import os
import shutil
import sys
import tempfile

from ubuntutools import getLogger
from ubuntutools.builder import get_builder
from ubuntutools.config import UDTConfig
from ubuntutools.sponsor_patch.sponsor_patch import check_dependencies, sponsor_patch

Logger = getLogger()


def parse(script_name):
    """Parse the command line parameters."""
    usage = (
        "%(prog)s [options] <bug number>\n"
        "One of --upload, --workdir, or --sponsor must be specified."
    )
    epilog = f"See {script_name}(1) for more info."
    parser = argparse.ArgumentParser(usage=usage, epilog=epilog)

    parser.add_argument(
        "-b",
        "--build",
        dest="build",
        help="Build the package with the specified builder.",
        action="store_true",
    )
    parser.add_argument(
        "-B", "--builder", dest="builder", help="Specify the package builder (default pbuilder)"
    )
    parser.add_argument(
        "-e",
        "--edit",
        help="launch sub-shell to allow editing of the patch",
        dest="edit",
        action="store_true",
    )
    parser.add_argument(
        "-k", "--key", dest="keyid", help="Specify the key ID to be used for signing."
    )
    parser.add_argument(
        "-l",
        "--lpinstance",
        dest="lpinstance",
        help="Launchpad instance to connect to (default: production)",
        metavar="INSTANCE",
    )
    parser.add_argument(
        "--no-conf",
        dest="no_conf",
        help="Don't read config files or environment variables.",
        action="store_true",
    )
    parser.add_argument(
        "-s",
        "--sponsor",
        help="sponsoring; equals -b -u ubuntu",
        dest="sponsoring",
        action="store_true",
    )
    parser.add_argument(
        "-u", "--upload", dest="upload", help="Specify an upload destination (default none)."
    )
    parser.add_argument(
        "-U",
        "--update",
        dest="update",
        action="store_true",
        help="Update the build environment before building.",
    )
    parser.add_argument(
        "-v", "--verbose", help="print more information", dest="verbose", action="store_true"
    )
    parser.add_argument(
        "-w",
        "--workdir",
        dest="workdir",
        help="Specify a working directory (default is a "
        "temporary directory, deleted afterwards).",
    )
    parser.add_argument("bug_number", type=int, help=argparse.SUPPRESS)

    args = parser.parse_args()
    if args.verbose:
        Logger.setLevel(logging.DEBUG)
    check_dependencies()

    config = UDTConfig(args.no_conf)
    if args.builder is None:
        args.builder = config.get_value("BUILDER")
    if args.lpinstance is None:
        args.lpinstance = config.get_value("LPINSTANCE")
    if not args.update:
        args.update = config.get_value("UPDATE_BUILDER", boolean=True)
    if args.workdir is None:
        args.workdir = config.get_value("WORKDIR")
    if args.keyid is None:
        args.keyid = config.get_value("KEYID")

    if args.sponsoring:
        args.build = True
        args.upload = "ubuntu"

    return args


def main():
    script_name = os.path.basename(sys.argv[0])
    args = parse(script_name)

    builder = get_builder(args.builder)
    if not builder:
        sys.exit(1)

    if not args.upload and not args.workdir:
        Logger.error("Please specify either a working directory or an upload target!")
        sys.exit(1)

    if args.workdir is None:
        workdir = tempfile.mkdtemp(prefix=script_name + "-")
    else:
        workdir = args.workdir

    try:
        sponsor_patch(
            args.bug_number,
            args.build,
            builder,
            args.edit,
            args.keyid,
            args.lpinstance,
            args.update,
            args.upload,
            workdir,
        )
    except KeyboardInterrupt:
        Logger.error("User abort.")
        sys.exit(2)
    finally:
        if args.workdir is None:
            shutil.rmtree(workdir)


if __name__ == "__main__":
    main()
