#!/bin/bash
set -euo pipefail

echo "[INFO] Starting Fluent Bit setup in Ubuntu container..."

# 安装必要的工具
echo "[INFO] Installing required packages..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq curl

# 解压bundle到/tmp
echo "[INFO] Extracting fluent-bit bundle..."
cp -r /private/etc /tmp
cp -r /private/packages /tmp
cd /tmp

# 安装 Fluent Bit 从 deb 包
echo "[INFO] Installing Fluent Bit from deb package..."
dpkg -i /tmp/packages/fluent-bit_3.1.9_amd64.deb || true
apt-get install -f -y -qq  # 解决依赖问题

# 验证 Fluent Bit 可以运行
echo "[INFO] Fluent Bit version:"
/opt/fluent-bit/bin/fluent-bit --version

# 创建配置目录
mkdir -p /etc/fluent-bit
cp -r /tmp/etc/* /etc/fluent-bit/

# 创建日志和缓冲区目录
mkdir -p /logs/train /logs/infer /buffers
chmod 755 /logs/train /logs/infer /buffers

# 等待 Elasticsearch 就绪
echo "[INFO] Waiting for Elasticsearch to be ready..."
while ! curl -fs http://${ES_HOST}:${ES_PORT}/_cluster/health >/dev/null 2>&1; do
    echo "  Waiting for ES at ${ES_HOST}:${ES_PORT}..."
    sleep 5
done
echo "[INFO] Elasticsearch is ready"

# 启动 Fluent Bit
echo "[INFO] Starting Fluent Bit with configuration from /etc/fluent-bit/"
echo "[INFO] Command: /opt/fluent-bit/bin/fluent-bit --config=/etc/fluent-bit/fluent-bit.conf"
exec /opt/fluent-bit/bin/fluent-bit \
    --config=/etc/fluent-bit/fluent-bit.conf
