#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_DIR=$(mktemp -d)
trap 'rm -rf "$TEST_DIR"' EXIT

FAKE_BIN="${TEST_DIR}/bin"
APP_DIR="${TEST_DIR}/app"
STATE_FILE="${TEST_DIR}/state"
CALLS_FILE="${TEST_DIR}/calls"
OUTPUT_FILE="${TEST_DIR}/output"
mkdir -p "$FAKE_BIN" "$APP_DIR"

cat > "${FAKE_BIN}/docker" <<'EOF'
#!/bin/bash

set -euo pipefail

case "$1" in
    inspect)
        container=${@: -1}
        state=$(cat "$EAGLE_LOGS_TEST_STATE_FILE")
        if { [ "$state" = "blue" ] && [ "$container" = "eagle-blue" ]; } ||
            { [ "$state" = "green" ] && [ "$container" = "eagle-green" ]; }; then
            echo true
        else
            echo false
        fi
        ;;
    logs)
        container=${@: -1}
        printf '%s\n' "$*" >> "$EAGLE_LOGS_TEST_CALLS_FILE"
        if [ "$container" = "eagle-blue" ]; then
            echo "last blue log"
            echo "eagle-green" > "$EAGLE_LOGS_TEST_ACTIVE_FILE"
            echo "green" > "$EAGLE_LOGS_TEST_STATE_FILE"
        else
            echo "first green log"
        fi
        ;;
    *)
        echo "Unexpected docker command: $*" >&2
        exit 1
        ;;
esac
EOF
chmod +x "${FAKE_BIN}/docker"

export EAGLE_LOGS_TEST_STATE_FILE="$STATE_FILE"
export EAGLE_LOGS_TEST_CALLS_FILE="$CALLS_FILE"
export EAGLE_LOGS_TEST_ACTIVE_FILE="${APP_DIR}/.active-instance"

echo "blue" > "$STATE_FILE"
echo "eagle-blue" > "${APP_DIR}/.active-instance"

PATH="${FAKE_BIN}:$PATH" APP_DIR="$APP_DIR" "${SCRIPT_DIR}/eagle-logs.sh" --no-follow -n 25
grep -q '^logs -n 25 eagle-blue$' "$CALLS_FILE"

: > "$CALLS_FILE"
echo "blue" > "$STATE_FILE"
echo "eagle-blue" > "${APP_DIR}/.active-instance"
PATH="${FAKE_BIN}:$PATH" APP_DIR="$APP_DIR" EAGLE_LOGS_RETRY_INTERVAL_SECONDS=0.01 \
    "${SCRIPT_DIR}/eagle-logs.sh" -n 10 > "$OUTPUT_FILE" 2>&1 &
FOLLOW_PID=$!

for _ in $(seq 1 100); do
    if grep -q 'first green log' "$OUTPUT_FILE"; then
        break
    fi
    sleep 0.01
done

kill "$FOLLOW_PID" 2>/dev/null || true
wait "$FOLLOW_PID" 2>/dev/null || true

grep -q 'EAGLE LOG STREAM DISCONNECTED' "$OUTPUT_FILE"
grep -q 'EAGLE LOG STREAM RESUMED' "$OUTPUT_FILE"
grep -q 'last blue log' "$OUTPUT_FILE"
grep -q 'first green log' "$OUTPUT_FILE"
grep -q '^logs --follow -n 10 eagle-blue$' "$CALLS_FILE"
grep -Eq '^logs --follow -n 10 --since [0-9]+ eagle-green$' "$CALLS_FILE"

echo "eagle-logs tests passed"
