#!/bin/sh

set -e
set -x

mkdir -p automake
cd automake

cat > configure.ac<<EOF
AC_INIT([foo], [2])
AC_CONFIG_SRCDIR([config.h.in])
AC_CONFIG_HEADERS([config.h])
AM_INIT_AUTOMAKE([foreign silent-rules parallel-tests])
AC_LANG([C++])
AC_PROG_CXX
AC_PROG_CXXCPP
AC_PROG_RANLIB
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
EOF

cat > Makefile.am <<EOF
lib_LIBRARIES = libfoo.a
libfoo_a_SOURCES = foo.cc

check_LIBRARIES = libtest.a
libtest_a_SOURCES = test.cc

TESTS = one.test two.test
TEST_EXTENSIONS = .test
AM_DEFAULT_SOURCE_EXT = .cc
EXTRA_PROGRAMS = \$(TESTS)

libtest_a_LIBADD = libfoo.a
LDADD = libtest.a libfoo.a
EOF

cat > foo.h <<EOF
#ifndef my_foo_h
#define my_foo_h
#include <string>
std::string foo(void);
#endif
EOF

cat > foo.cc <<EOF
#include <config.h>
#include "foo.h"
std::string foo(void) { return "fu"; }

EOF

cat > one.cc <<EOF
#include <config.h>
#include "foo.h"
#include "test.h"
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
	init(argc, argv);
	std::cout << "Hello World!\n" << foo() << "\n";
	return 0;
}
EOF

cat > two.cc <<EOF
#include <config.h>
#include "foo.h"
#include "test.h"
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
	init(argc, argv);
	std::string str = foo();
	if (str != "foo") {
	   std::cerr << "error: foo(): " << str << "\n";
	   return 1;
	}
	return 0;
}
EOF

cat > test.h <<EOF
#ifndef my_test_h
#define my_test_h
void init(int argc, char* argv[]);
#endif
EOF

cat > test.cc <<EOF
#include <config.h>
#include "test.h"
#include "foo.h"
#include <iostream>
void init(int argc, char* argv[])
{
	std::cout << "init test for " << foo() << "\n";
}
EOF


autoreconf -ivf
./configure --enable-silent-rules
make all -j8
make check -j8 || echo failed as expected

sed 's,"fu","foo",' < foo.cc > foo.cc-t && mv foo.cc-t foo.cc

make recheck -j16
