#!/usr/bin/env python3

import argparse
import os
import shutil
import subprocess

parser = argparse.ArgumentParser()

parser.add_argument('--meson', help='path to meson binary',
                    type=str, required=True)
parser.add_argument('--meson_args', help='args of meson binary',
                    type=str, nargs='*', required=False)
parser.add_argument('--input', help='input meson-test.build file',
                    type=str, required=True)
parser.add_argument('--test_dir', help='test directory',
                    type=str, required=True)
parser.add_argument('--test_source_dir', help='test source directory',
                    type=str, required=True)
parser.add_argument('--builddir', help='meson build directory',
                    type=str, required=True)
parser.add_argument('--pkg_conf_path',
                    help='PKG_CONF_PATH from surrounding meson build',
                    type=str, nargs='?', const='', required=False)
parser.add_argument('c_args', help='c_args from surrounding meson build',
                     nargs='*')

args = parser.parse_args()

meson_bin = args.meson
meson_args = args.meson_args or []
input = args.input
test_dir = args.test_dir
test_source_dir = args.test_source_dir
build_dir = args.builddir
pkg_conf_path = args.pkg_conf_path
c_args = ' '.join(args.c_args)

def remove_duplicates(duplicate_str):
    # Remove duplicates based on basename as there could be a mix of both full
    # paths and bare binary names.
    words = [os.path.basename(word) for word in duplicate_str.split()]
    return ' '.join(sorted(set(words), key=words.index))


def run_tests(pkg_conf_path_local, message):
    print('\n{}\n{}\n'.format('#' * 60, message), flush=True)

    test_out_dir = 'build'
    test_args = f'-Dmeson_source_dir={test_source_dir}'

    env = {**os.environ, }
    env['PKG_CONFIG_PATH'] = '{}:{}:{}'.format(
      pkg_conf_path_local, pkg_conf_path, env.get('PKG_CONFIG_PATH', ''),
    ).strip(': ')
    env['CC'] = '{} {}'.format(
      c_args, env.get('CC', ''),
    )
    env['CC'] = remove_duplicates(env['CC'])

    # Copy input file to test directory and rename it as a meson.build
    if os.path.exists(test_dir):
        shutil.rmtree(test_dir)
    os.makedirs(test_dir)
    shutil.copyfile(input, os.path.join(test_dir, 'meson.build'))

    # Put meson_options.txt to the test_dir so that we can pass
    # meson_source_dir argument
    with open(os.path.join(test_dir, 'meson_options.txt'), 'w') as f:
        f.write("option('meson_source_dir', type: 'string', value: '',\n"
                "  description: 'Actual source directory of the meson-test.build file')\n")

    meson_setup_command = [meson_bin, *meson_args, 'setup', test_args, test_out_dir]
    meson_compile_command = [meson_bin, 'compile', '-C', test_out_dir, '-v']

    subprocess.run(meson_setup_command, env=env, cwd=test_dir, check=True)
    subprocess.run(meson_compile_command, cwd=test_dir, check=True)

run_tests(os.path.join(build_dir, 'meson-uninstalled'),
          message='Testing postgresql-extension-warnings-uninstalled')
