#!/usr/bin/python3
#
# Copyright (c) 2018, 2019  Peter Pentchev <roam@ringlet.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

"""
Generate shell scripts with TAP output for the confget tests.
"""

from typing import List

from unit_tests.data import defs as t_defs
from unit_tests.data import load as t_load
from unit_tests.data import util as t_util


PRELUDE = r"""#!/bin/sh
#
# Copyright (c) 2008, 2011, 2019  Peter Pentchev
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

[ -z "$CONFGET" ] && CONFGET='./confget'
[ -z "$TESTDIR" ] && TESTDIR='t'

echo '1..{count}'
"""

CHECK_TESTFILE = r"""
if [ ! -f "$TESTDIR/{fname}" ]; then
        echo "Bail out!  No test file $TESTDIR/{fname}"
        exit 255
fi"""


def add_cmdline_options(cmdline: List[str], test: t_defs.TestDef) -> None:
    """ Add the options from test.args into cmdline. """
    for name, value in test.args.items():
        option = t_defs.CMDLINE_OPTIONS[name]
        if option[0] == "":
            continue
        cmdline.append(f"'{option[0]}'")
        if option[1]:
            if name == "filename":
                cmdline.append(f'"$TESTDIR/{value}"')
            else:
                cmdline.append(t_util.shell_escape(value))


def main() -> None:
    """ Main function: generate the test files. """
    tests = t_load.load_all_tests(".")
    for fname, data in sorted(tests.items()):
        print(f"Generating {fname}.t with {len(data.tests)} tests")
        with open(f"{fname}.t", mode="w") as testf:
            print(PRELUDE.format(count=len(data.tests)), file=testf)

            filenames = sorted(
                {
                    test.args["filename"]
                    for test in data.tests
                    if "filename" in test.args
                }
            )
            for filename in filenames:
                print(CHECK_TESTFILE.format(fname=filename), file=testf)

            for idx, test in enumerate(data.tests):
                tap_idx = idx + 1

                cmdline: List[str] = []
                if test.setenv:
                    cmdline.append("env")
                    for name, value in sorted(data.setenv.items()):
                        cmdline.append(f"{name}={t_util.shell_escape(value)}")

                cmdline.append("$CONFGET")
                if test.backend != "ini":
                    cmdline.extend(["-t", test.backend])

                add_cmdline_options(cmdline, test)

                if test.stdin is not None:
                    cmdline.extend(
                        [t_defs.CMDLINE_OPTIONS["filename"][0], "-"]
                    )

                cmdline.extend([f"'{key}'" for key in test.keys])

                if test.stdin is not None:
                    cmdline.extend(["<", f'"$TESTDIR/{test.stdin}"'])

                xform = t_defs.XFORM[test.xform].command
                print(f'- {tap_idx}: {" ".join(cmdline)} {xform}')

                print(f'v=`{" ".join(cmdline)} {xform}`', file=testf)
                print('res="$?"', file=testf)

                check = test.output.get_check()
                print(f"  - {check}")
                print(
                    f"if {check}; then echo 'ok {tap_idx}'; else "
                    f'echo "not ok {tap_idx} {test.output.var_name} is '
                    f"'${test.output.var_name}'\"; fi",
                    file=testf,
                )


if __name__ == "__main__":
    main()
