#!/bin/bash

if [ -z "$TELEGRAF_HOSTNAME" ]; then
    echo "Error: TELEGRAF_HOSTNAME is not set"
    exit 1
fi

if [ -z "$TELEGRAF_MONGODB_DSN" ]; then
    echo "Error: TELEGRAF_MONGODB_DSN is not set"
    exit 1
fi

if [ -z "$TELEGRAF_MONGODB_DATABASE" ]; then
    echo "Error: TELEGRAF_MONGODB_DATABASE is not set"
    exit 1
fi

if [ -z "$SOCKET_PORT" ]; then
    echo "Error: SOCKET_PORT is not set"
    exit 1
fi

if [ -z "$VIDEO_URL" ]; then
    echo "Error: VIDEO_URL is not set"
    exit 1
fi

# Set the environment variables
export DSN=$TELEGRAF_MONGODB_DSN
export DATABASE=$TELEGRAF_MONGODB_DATABASE
export HOSTNAME=$TELEGRAF_HOSTNAME

# Start the Selenium hub
/opt/bin/entry_point.sh > /dev/null 2>&1 &

# Wait for Selenium hub to be ready
printf 'Waiting for Selenium standalone to be ready'
timeout=30
while ! curl -sSL "http://localhost:4444/wd/hub/status" 2>/dev/null | jq -e '.value.ready' | grep -q true; do
    printf '.'
    sleep 1
    ((timeout--))
    if [ $timeout -le 0 ]; then
        echo "Error: Selenium standalone did not become ready in time. Exiting..."
        exit 1
    fi
done

printf '\n'

# Start the Telegraf agent
telegraf --config ./telegraf.conf &

# Start the main Python script as PID 1
exec ./venv/bin/python main.py