#!/usr/bin/env bash
set -euo pipefail

# 获取fluent-bit-host02容器名称
container_name="logging-mvp-fluent-bit-host02-1"

wait_for_container() {
    local name="$1"
    local attempts=30
    local delay=5
    local i
    for ((i = 1; i <= attempts; i++)); do
        if docker ps --format '{{.Names}}' | grep -Fx "$name" >/dev/null; then
            return 0
        fi
        echo "[INFO] 等待容器 $name 启动中... ($i/$attempts)"
        sleep "$delay"
    done
    return 1
}

if ! wait_for_container "$container_name"; then
    echo "[ERROR] Fluent Bit容器 $container_name 未运行"
    exit 1
fi

# 创建日志目录
docker exec "$container_name" mkdir -p /logs/train /logs/infer

# 写入训练日志 (host02)
docker exec "$container_name" sh -c "printf '%s INFO [host02] training step=1 loss=1.45 model=gpt\n' \"\$(date '+%F %T')\" >> /logs/train/train-demo.log"
docker exec "$container_name" sh -c "printf '%s INFO [host02] training step=2 loss=1.38 model=gpt\n' \"\$(date '+%F %T')\" >> /logs/train/train-demo.log"
docker exec "$container_name" sh -c "printf '%s INFO [host02] training step=3 loss=1.32 model=gpt\n' \"\$(date '+%F %T')\" >> /logs/train/train-demo.log"

# 写入推理日志 (host02)  
docker exec "$container_name" sh -c "printf '%s WARN [host02] inference slow on batch=5 latency=2.3s\n' \"\$(date '+%F %T')\" >> /logs/infer/infer-demo.log"
docker exec "$container_name" sh -c "printf '%s INFO [host02] inference completed batch=6 latency=0.8s\n' \"\$(date '+%F %T')\" >> /logs/infer/infer-demo.log"

echo "[OK] 已通过docker exec写入测试日志到 host02 容器内："
echo " - /logs/train/train-demo.log"
echo " - /logs/infer/infer-demo.log"
