#!/bin/bash
# Firefrost Automation Executor
# Runs queued commands and commits results back to Git

set -e  # Exit on error

QUEUE_DIR="/root/firefrost-work/firefrost-operations-manual/automation/queue"
RESULTS_DIR="/root/firefrost-work/firefrost-operations-manual/automation/results"
LOG_DIR="/root/firefrost-work/firefrost-operations-manual/automation/logs"
REPO_DIR="/root/firefrost-work/firefrost-operations-manual"

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

# Change to repo directory
cd "$REPO_DIR"

# Pull latest from Git
log "Pulling latest from Git..."
git pull origin master || log "WARNING: Git pull failed, continuing with local"

# Check for queued tasks
TASKS=$(find "$QUEUE_DIR" -name "*.sh" -type f | sort)

if [ -z "$TASKS" ]; then
    log "No tasks in queue"
    exit 0
fi

# Process each task
for TASK in $TASKS; do
    TASK_NAME=$(basename "$TASK")
    RESULT_FILE="$RESULTS_DIR/${TASK_NAME%.sh}_result.txt"
    
    log "=========================================="
    log "Executing task: $TASK_NAME"
    log "=========================================="
    
    # Execute task and capture output
    {
        echo "Task: $TASK_NAME"
        echo "Started: $(date)"
        echo "=========================================="
        bash "$TASK" 2>&1
        EXIT_CODE=$?
        echo "=========================================="
        echo "Finished: $(date)"
        echo "Exit Code: $EXIT_CODE"
    } > "$RESULT_FILE"
    
    # Move task to completed (remove from queue)
    mv "$TASK" "$LOG_DIR/${TASK_NAME%.sh}_completed_$(date +%Y%m%d_%H%M%S).sh"
    
    log "Task $TASK_NAME completed (exit code: $EXIT_CODE)"
done

# Commit results back to Git
log "Committing results to Git..."
git add automation/results/*.txt automation/logs/*.sh 2>/dev/null || true
git commit -m "Automation: Task execution results $(date '+%Y-%m-%d %H:%M:%S')" || log "Nothing to commit"
git push origin master || log "WARNING: Git push failed"

log "Executor run complete"
