#!/bin/bash
set -e

# Entrypoint script for socktop webterm container
# This script handles initialization and starts services

echo "==================================="
echo "Starting socktop webterm container"
echo "==================================="

# Function to verify config files are mounted correctly
copy_config_files() {
    echo "Checking for configuration files..."

    # Verify Alacritty configuration
    if [ -f "/home/socktop/.config/alacritty/alacritty.toml" ]; then
        echo "  ✓ alacritty.toml is mounted"
    else
        echo "  WARNING: alacritty.toml not found"
    fi

    # Verify Catppuccin Frappe theme
    if [ -f "/home/socktop/.config/alacritty/catppuccin-frappe.toml" ]; then
        echo "  ✓ catppuccin-frappe.toml is mounted"
    else
        echo "  WARNING: catppuccin-frappe.toml not found"
    fi

    # Verify socktop profiles.json
    if [ -f "/home/socktop/.config/socktop/profiles.json" ]; then
        echo "  ✓ profiles.json is mounted"
    else
        echo "  WARNING: profiles.json not found"
    fi

    # Check for TLS certificates
    echo "Checking for TLS certificates..."
    for key in rpi-master.pem rpi-worker-1.pem rpi-worker-2.pem rpi-worker-3.pem; do
        if [ -f "/home/socktop/.config/socktop/certs/$key" ]; then
            echo "  ✓ $key found"
        else
            echo "  - $key not found (optional)"
        fi
    done
}

# Set up Alacritty as default terminal
setup_alacritty() {
    echo "Setting up Alacritty as default terminal..."

    # Set TERM environment variable (already set in deployment env)
    export TERM=alacritty

    echo "Alacritty setup complete"
}

# Start socktop agent
start_socktop_agent() {
    echo "Starting socktop-agent on port 3001..."

    # Start socktop-agent in the background on port 3001
    /usr/bin/socktop_agent --port 3001 > /tmp/socktop-agent.log 2>&1 &
    AGENT_PID=$!

    echo "socktop-agent started (PID: $AGENT_PID)"

    # Give it a moment to start
    sleep 1

    # Check if it's running
    if kill -0 $AGENT_PID 2>/dev/null; then
        echo "  ✓ socktop-agent is running on port 3001"
    else
        echo "  ⚠ socktop-agent may have failed to start (check /tmp/socktop-agent.log)"
    fi
}

# Main initialization
main() {
    echo "Running initialization..."

    # Copy configuration files
    copy_config_files

    # Set up Alacritty
    setup_alacritty

    # Start socktop agent
    start_socktop_agent

    echo ""
    echo "==================================="
    echo "Initialization complete!"
    echo "==================================="
    echo ""
    echo "Services:"
    echo "  - Webterm: http://localhost:8082"
    echo "  - Socktop Agent: ws://localhost:3001/ws"
    echo ""

    # Execute the main command
    exec "$@"
}

# Run main function
main "$@"
