#! /usr/bin/env bash

# Sleeps until a file comes into existence.

if [[ $# -ne 2 ]]; then
    echo >&2 "usage: $0 <file to wait for> <max secs to wait>"
    exit 1
fi

SLEEP_INTERVAL=0.1
SLEEP_INTERVAL_MS=100

wait_file=$1
max_wait=$2
# Avoid floating point arithmetic by using milliseconds
wait_countdown=$((${max_wait}000 / SLEEP_INTERVAL_MS))

while [[ ! -e $wait_file ]]; do
    wait_countdown=$((wait_countdown - 1))

    if [[ $wait_countdown -le 0 ]]; then
        echo >&2 "error: file '$wait_file' does not exist after $max_wait seconds"
        exit 1
    fi

    sleep $SLEEP_INTERVAL
done
