#!/bin/sh
# watershed test
# Author: Martin Pitt <martin.pitt@ubuntu.com>
set -eu

WORKDIR=$(mktemp --tmpdir -d watershed.test.XXXXXX)
trap "rm -rf $WORKDIR" EXIT INT QUIT PIPE

TRACEDIR="$WORKDIR/trace"
STATEDIR="$WORKDIR/state"

# process start time plus pid is an unique string
CMD="sleep \$SLEEP; touch $TRACEDIR/\$\$.\$(stat -c %Z /proc/\$\$)"

reset() {
    rm -rf $TRACEDIR $STATEDIR
    mkdir -p $TRACEDIR $STATEDIR
}

assert_two_runs() {
    if [ "$(ls $TRACEDIR | wc -l)" != 2 ]; then
        echo "FAIL: Expecting two runs, but got:" >&2
        ls -l $TRACEDIR >&2
        exit 1
    fi
}

# we run 10 parallel instances of watershed, with increasing sleep (command
# duration); in all cases we expect the command to run exactly twice
for sleep in $(LC_ALL=C seq 0 0.1 1); do
    echo
    echo "=== Testing with sleep $sleep ==="
    export SLEEP=$sleep

    reset
    for inst in `seq 10`; do
        ./watershed -d $STATEDIR sh -c "$CMD" &
    done
    wait
    assert_two_runs
done
