#!/bin/sh
set -e

TOKEN="$$.$(date +%s)"
REQ_FILE="/tmp/nginx.reload.request.${TOKEN}"
RES_FILE="/tmp/nginx.reload.result.${TOKEN}"
LOG_FILE="/tmp/nginx.reload.log.${TOKEN}"

touch "$REQ_FILE"

i=0
while [ $i -lt 50 ]; do
    if [ -s "$RES_FILE" ]; then
        break
    fi
    i=$((i + 1))
    sleep 0.1
done

if [ ! -f "$RES_FILE" ]; then
    echo "Reload timeout"
    exit 1
fi

if grep -q '^OK$' "$RES_FILE"; then
    echo "OK"
    exit 0
fi

if [ -f "$LOG_FILE" ]; then
    cat "$LOG_FILE"
fi
exit 1
