#!/bin/sh
#
# wait up to TIMEOUT seconds until a WAIT_ON_FILE is created.
#
# In addition, this script can create CREATE_FILE once it is ready to wait.

if [ $# -lt 2 ] || [ $# -gt 3 ]; then
    echo $#
    echo "USAGE: $0 TIMEOUT WAIT_ON_FILE [CREATE_FILE]"
fi

timer="$1"

# If the test timeout have been extended, also scale the timer relative
# to the normal timing.
if [ "100" -lt "$HGTEST_TIMEOUT_PERCENTAGE" ]; then
    timer=$(( ( $timer * $HGTEST_TIMEOUT_PERCENTAGE ) / 100 ))
fi

max_time=$timer

# Scale the timeout to match the sleep steps below, i.e. 1/0.02.
timer=$(( 50 * $timer ))

wait_on="$2"
create=""
if [ $# -eq 3 ]; then
    create="$3"
fi

if [ -n "$create" ]; then
    touch "$create"
    create=""
fi
while [ "$timer" -gt 0 ] && !([ -e "$wait_on" ] || [ -L "$wait_on" ]) ; do
    timer=$(( $timer - 1))
    sleep 0.02
done
if [ "$timer" -le 0 ]; then
    echo "file not created after $max_time seconds: $wait_on" >&2
    exit 1
fi
