#!/bin/bash

# ParentZone Downloader Startup Script
# This script starts both cron and the web server

set -e

LOG_DIR="/app/logs"
SNAPSHOTS_DIR="/app/snapshots"

# Create directories if they don't exist
mkdir -p "$LOG_DIR"
mkdir -p "$SNAPSHOTS_DIR"

# Function to log messages with timestamp
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - STARTUP - $1" | tee -a "$LOG_DIR/startup.log"
}

log_message "=== ParentZone Downloader Starting ==="

# Start cron daemon
log_message "Starting cron daemon..."
cron

# Create log file for cron output
touch /var/log/cron.log

log_message "Cron daemon started"

# Start web server in the background
log_message "Starting web server on port 8080..."
python3 webserver.py --host 0.0.0.0 --port 8080 --snapshots-dir "$SNAPSHOTS_DIR" &
WEB_SERVER_PID=$!

log_message "Web server started with PID: $WEB_SERVER_PID"
log_message "Web interface available at http://localhost:8080"

# Function to handle shutdown
shutdown() {
    log_message "=== Shutdown Signal Received ==="

    if [ ! -z "$WEB_SERVER_PID" ]; then
        log_message "Stopping web server (PID: $WEB_SERVER_PID)..."
        kill "$WEB_SERVER_PID" 2>/dev/null || true
        wait "$WEB_SERVER_PID" 2>/dev/null || true
        log_message "Web server stopped"
    fi

    log_message "Stopping cron daemon..."
    pkill cron 2>/dev/null || true

    log_message "=== ParentZone Downloader Shutdown Complete ==="
    exit 0
}

# Set up signal handlers
trap shutdown SIGTERM SIGINT

log_message "=== ParentZone Downloader Started Successfully ==="
log_message "Services running:"
log_message "  - Cron daemon (scheduled downloads)"
log_message "  - Web server at http://0.0.0.0:8080"
log_message "  - Log files in: $LOG_DIR"
log_message "  - Snapshots in: $SNAPSHOTS_DIR"

# Keep the container running and follow cron logs
tail -f /var/log/cron.log &
TAIL_PID=$!

# Wait for any process to exit
wait $WEB_SERVER_PID $TAIL_PID
