#!/bin/bash

# Install Filebeat package
echo "INSTALLING FILEBEAT"

# Función para esperar a que el lock de dpkg esté libre
wait_for_dpkg_lock() {
    while fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 ; do
        echo "Esperando a que el lock de dpkg se libere..."
        sleep 5
    done
}

# Esperar máximo 2 minutos hasta que dpkg esté listo
wait_for_dpkg_lock


dpkg -i --force-overwrite /usr/share/OGAgent/filebeat/filebeat-oss-7.12.1-amd64.deb

# Copy certificates and configuration
cp /usr/share/OGAgent/filebeat/CA/ogagent-fb.mytld.crt.pem /etc/filebeat/
cp /usr/share/OGAgent/filebeat/CA/ogagent-fb.mytld.key.pem /etc/filebeat/
cp /usr/share/OGAgent/filebeat/CA/ca.crt.pem /etc/ssl/certs/
cp /usr/share/OGAgent/filebeat/filebeat.yml /etc/filebeat/filebeat.yml

# Add entry to /etc/hosts
oglog_ip="${OGAGENTCFG_OGLOG_IP:-192.168.2.1}"
echo "${oglog_ip} oglog-os.mytld" >> /etc/hosts

# Start Filebeat
/usr/bin/filebeat --environment systemd -c /etc/filebeat/filebeat.yml --path.home /usr/share/filebeat --path.config /etc/filebeat --path.data /var/lib/filebeat --path.logs /var/log/filebeat &
