#!/bin/sh
set -eu

waf=${WAF:-/usr/bin/waf}
work_dir=$(mktemp -d "${AUTOPKGTEST_TMP:-${TMPDIR:-/tmp}}/waf-build.XXXXXX")
trap 'rm -rf "$work_dir"' EXIT HUP INT TERM
export PYTHONDONTWRITEBYTECODE=1
unset WAFDIR
cd "$work_dir"

cat > wscript <<'PY'
top = '.'
out = 'build'

def options(opt):
    opt.load('compiler_c')

def configure(conf):
    conf.load('compiler_c')
    conf.load('gccdeps')

def build(bld):
    bld.program(source='main.c', target='hello', install_path='${BINDIR}')
PY

cat > main.c <<'C'
#include <stdio.h>
#include "greeting.h"
int main(void) {
    puts(GREETING);
    return 0;
}
C
echo '#define GREETING "waf packaging test"' > greeting.h

"$waf" --version
"$waf" configure --prefix=/usr --color=no
"$waf" build --color=no -j2 --verbose
test "$(build/hello)" = 'waf packaging test'

# An unchanged build must keep the existing output.
timestamp=$(stat -c %y build/hello)
"$waf" build --color=no -j2 --verbose
test "$(stat -c %y build/hello)" = "$timestamp"

# Changing a header must rebuild the executable, including with gccdeps.
echo '#define GREETING "rebuilt by waf"' > greeting.h
"$waf" build --color=no -j2 --verbose
test "$(build/hello)" = 'rebuilt by waf'

"$waf" install --destdir="$work_dir/stage" --color=no --verbose
test "$(stage/usr/bin/hello)" = 'rebuilt by waf'
"$waf" uninstall --destdir="$work_dir/stage" --color=no
test ! -e stage/usr/bin/hello
"$waf" clean --color=no
test ! -e build/hello
"$waf" distclean --color=no
test ! -d build
