#!/bin/bash
# Firefrost Automation Daemon
# Watches for new tasks in Git and executes them

REPO_DIR="/root/firefrost-work/firefrost-operations-manual"
LOG_DIR="$REPO_DIR/automation/logs"
EXECUTOR="$REPO_DIR/automation/executor.sh"
CHECK_INTERVAL=10  # Check every 10 seconds

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

log "=========================================="
log "Firefrost Automation Daemon Starting"
log "Check Interval: ${CHECK_INTERVAL}s"
log "=========================================="

cd "$REPO_DIR"

while true; do
    # Pull latest from Git (quietly)
    git pull origin master &>/dev/null
    
    # Check if there are tasks in queue
    TASK_COUNT=$(find automation/queue -name "*.sh" -type f 2>/dev/null | wc -l)
    
    if [ "$TASK_COUNT" -gt 0 ]; then
        log "Found $TASK_COUNT task(s) in queue - executing..."
        bash "$EXECUTOR"
    fi
    
    # Wait before next check
    sleep "$CHECK_INTERVAL"
done
