#!/bin/bash

# Configuration
ARTISAN_PATH="/home4/tcikl9rl/staging.mycloud.mu/artisan"
LOG_DIR="/home4/tcikl9rl/staging.mycloud.mu/storage/logs"
QUEUE_LOG="$LOG_DIR/queue.log"
ERROR_LOG="$LOG_DIR/queue-error.log"
LOCK_FILE="/tmp/queue_worker.lock"
MEMORY_LIMIT=512
TRIES=3
TIMEOUT=300
MAX_RUNTIME=1800 # Max runtime for this script (in seconds, 30 minutes)

# Ensure the log directory exists
mkdir -p "$LOG_DIR"

# Trap signals for graceful shutdown
trap "on_exit" SIGINT SIGTERM

# Function to handle cleanup on exit
on_exit() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Received shutdown signal. Cleaning up and exiting." >> "$ERROR_LOG"
    rm -f "$LOCK_FILE"
    exit 0
}

# Function to create a lock file
create_lock() {
    if [[ -f "$LOCK_FILE" ]]; then
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script is already running. Exiting to prevent multiple instances." >> "$ERROR_LOG"
        exit 1
    fi
    echo $$ > "$LOCK_FILE"
}

# Function to remove the lock file
remove_lock() {
    rm -f "$LOCK_FILE"
}

# Function to run the queue worker until the script reaches max runtime
run_worker_until_timeout() {
    START_TIME=$(date +%s)
    while :; do
        php "$ARTISAN_PATH" queue:work \
            --memory="$MEMORY_LIMIT" \
            --tries="$TRIES" \
            --timeout="$TIMEOUT" \
            --sleep=5 \
            >> "$QUEUE_LOG" \
            2>> "$ERROR_LOG"

        # Break loop if the runtime exceeds the maximum allowed time
        CURRENT_TIME=$(date +%s)
        if (( CURRENT_TIME - START_TIME >= MAX_RUNTIME )); then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] Reached max runtime. Exiting." >> "$QUEUE_LOG"
            break
        fi
    done
}

# Main process
main() {
    create_lock
    run_worker_until_timeout
    remove_lock
}

# Run the main function
main