#!/bin/bash
# Init script for What-If Shorts bot.
# Sets up Xvfb, Chrome, directories, and verifies dependencies.
set -e

export PATH=/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin
export DISPLAY=:50
BOT_DIR=/home/melon/public_html/shorts
CHROME_PROFILE=/home/melon/.chrome_whatif_profile

echo "=== What-If Shorts Bot Init ==="

# Create required directories
mkdir -p "$BOT_DIR/output" "$BOT_DIR/downloads" "$BOT_DIR/logs"
echo "[OK] Directories ready"

# Start Xvfb if not running
if ! pgrep -f "Xvfb :50" >/dev/null 2>&1; then
    Xvfb :50 -screen 0 1920x1080x24 &
    sleep 2
    echo "[OK] Xvfb started on :50"
else
    echo "[OK] Xvfb already running on :50"
fi

# Start Chrome if not running
if ! pgrep -f "chrome.*whatif_profile.*9222" >/dev/null 2>&1; then
    google-chrome --no-sandbox --disable-gpu \
        --user-data-dir="$CHROME_PROFILE" \
        --start-maximized \
        --remote-debugging-port=9222 \
        about:blank &>/dev/null &
    sleep 5
    echo "[OK] Chrome started with debugging port 9222"
else
    echo "[OK] Chrome already running with debugging port 9222"
fi

# Find Python
if [ -x /bin/python3.12 ]; then
    PY=/bin/python3.12
elif command -v python3.12 >/dev/null 2>&1; then
    PY=$(command -v python3.12)
else
    PY=/bin/python3
fi
echo "[OK] Python: $PY ($($PY --version 2>&1))"

# Verify key dependencies
echo -n "[CHECK] ffmpeg: "; ffmpeg -version 2>&1 | head -1
echo -n "[CHECK] convert: "; convert --version 2>&1 | head -1
echo -n "[CHECK] Chrome: "; google-chrome --version 2>&1

echo ""
echo "=== Init complete. Ready to run. ==="
