#!/bin/sh

# Generate test suite for each source file containing "^START_TEST":
for f in *.c; do
	tests=$(grep ^START_TEST $f | cut -c 12- | sed 's/).*//')
	suitefn=$(echo ${f%.*} | sed 's/-/_/g')
	cppname=$(echo ${f%.*} | sed 's/-/_/g' | tr [:lower:] [:upper:])

	# Continue if no tests.
        if [ -z "$tests" ]; then
                continue
        fi

        cat <<EOF > ${f%.*}-suite.h
/* Machine-generated by $0; do not edit. */

#ifndef _${cppname}_SUITE_H

Suite *dmap_test_${suitefn}(void);

#endif
EOF

        cat <<EOF > ${f%.*}-suite.c
/* Machine-generated by $0; do not edit. */

#include "${f%.*}-suite.h"

Suite *dmap_test_${suitefn}(void)
{
        TCase *tc;
        Suite *s = suite_create("${suitefn}");

EOF
        for t in $tests; do
                cat <<EOF >> ${f%.*}-suite.c
        tc = tcase_create("$t");
        tcase_add_test(tc, $t);
        suite_add_tcase(s, tc);

EOF
        done

        cat <<EOF >> ${f%.*}-suite.c
        return s;
}
EOF
done

# Generate unit-test.c which invokes each test suite:
cat <<EOF > unit-test.c
/* Machine-generated by $0; do not edit. */

#include <check.h>
#include <glib.h>
#include <stdlib.h>
#include <libdmapsharing/dmap.h>

EOF

for f in *.c; do
        # Get list of tests in given source file.
        tests=$(grep ^START_TEST $f | cut -c 12- | sed 's/).*//')
	suitefn=$(echo ${f%.*} | sed 's/-/_/g')

        # Continue if no tests.
        if [ -z "$tests" ]; then
                continue
        fi
        cat <<EOF >> unit-test.c
#include "../libdmapsharing/${f%.*}-suite.h"
EOF
done

cat <<EOF >> unit-test.c

static void
debug_null (const char *log_domain,
            GLogLevelFlags log_level,
            const gchar *message,
            gpointer user_data)
{
}

void run_suite (Suite *s)
{
        int nf;
        SRunner *sr;

        sr = srunner_create(s);
        srunner_run_all(sr, CK_NORMAL);
        nf = srunner_ntests_failed(sr);
        srunner_free(sr);
        if (nf != 0) {
                exit (EXIT_FAILURE);
	}
}

int main(void)
{
        g_log_set_handler ("libdmapsharing", G_LOG_LEVEL_DEBUG, debug_null, NULL);
        g_log_set_handler (NULL, G_LOG_LEVEL_DEBUG, debug_null, NULL);
EOF

for f in *.c; do
        # Get list of tests in given source file.
        tests=$(grep ^START_TEST $f | cut -c 12- | sed 's/).*//')
	suitefn=$(echo ${f%.*} | sed 's/-/_/g')

        # Continue if no tests.
        if [ -z "$tests" ]; then
                continue
        fi
        cat <<EOF >> unit-test.c
        run_suite(dmap_test_${suitefn}());
EOF
done

cat <<EOF >> unit-test.c

        exit (EXIT_SUCCESS);
}
EOF
