#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2026 Romain Maneschi <romain@gitroot.dev>
#
# SPDX-License-Identifier: EUPL-1.2

_init() {
    local SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
    source "${SCRIPT_DIR}/report.sh"
}

_init
unset -f _init

# wait_for_logs <logToWaitTo> <fileOfLogs> <opt afterLogs>
#   Wait for a line which contain <logToWaitTo> after <opt afterLogs> in the <fileOfLogs>.
function wait_for_logs() {
    local pattern="$1"
    local log_file="$2"
    local after_pattern="$3"
    local timeout=30
    local start_time=$(date +%s)

    if [[ ! -f "$log_file" ]]; then
        report "🛑 Error: File $log_file not found."
        return 1
    fi

    if [[ -n "$after_pattern" ]]; then
        ( tail -n +1 -f "$log_file" | sed -u -n "/$after_pattern/,/$pattern/ { p; /$pattern/q; }" > /dev/null ) &
    else
        ( tail -n +1 -f "$log_file" | grep -q "$pattern" > /dev/null ) &
    fi
    
    local pid=$!

    ( sleep "$timeout"; kill "$pid" 2>/dev/null ) &
    local timeout_pid=$!

    wait "$pid" 2>/dev/null
    local exit_code=$?

    kill "$timeout_pid" 2>/dev/null

    if [[ $exit_code -ne 0 ]]; then
        report "🛑 Timeout reached waiting for '$pattern' in $log_file"
        return 1
    fi

    local end_time=$(date +%s)
    report "🕐 Found '$pattern' in $((end_time - start_time)) seconds"
    return 0
}