#!/bin/bash
#
# SUPERVISOR INSTALLATION SCRIPT FOR AIDEPOS QUEUE WORKERS
# =========================================================
#
# This script installs and configures Supervisor to manage Laravel queue workers
# with proper timeout settings for long-running sync jobs.
#
# USAGE:
#   chmod +x install-supervisor.sh
#   sudo ./install-supervisor.sh
#

set -e  # Exit on error

echo "=================================================="
echo "AIDEPOS QUEUE WORKER SUPERVISOR SETUP"
echo "=================================================="
echo ""

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}ERROR: Please run as root or with sudo${NC}"
    exit 1
fi

# Step 1: Install Supervisor
echo -e "${YELLOW}Step 1: Installing Supervisor...${NC}"
if command -v supervisorctl &> /dev/null; then
    echo -e "${GREEN}✓ Supervisor is already installed${NC}"
else
    if ! command -v apt-get &> /dev/null; then
        echo -e "${RED}ERROR: This installer only supports Debian/Ubuntu (apt-get). Install Supervisor manually for your distro.${NC}"
        exit 1
    fi
    echo "Installing Supervisor..."
    apt-get update
    apt-get install -y supervisor
    echo -e "${GREEN}✓ Supervisor installed successfully${NC}"
fi
echo ""

# Step 2: Get configuration details
echo -e "${YELLOW}Step 2: Configuration${NC}"
read -p "Enter Laravel application path [/home/aideeicq/Aidepos]: " APP_PATH
APP_PATH=${APP_PATH:-/home/aideeicq/Aidepos}

read -p "Enter web server user [aideeicq]: " WEB_USER
WEB_USER=${WEB_USER:-aideeicq}

read -p "Enter PHP binary path [/usr/local/bin/php]: " PHP_PATH
PHP_PATH=${PHP_PATH:-/usr/local/bin/php}

read -p "Enter number of worker processes [2]: " NUM_PROCS
NUM_PROCS=${NUM_PROCS:-2}

echo ""
echo "Configuration:"
echo "  App Path: $APP_PATH"
echo "  User: $WEB_USER"
echo "  PHP: $PHP_PATH"
echo "  Workers: $NUM_PROCS"
echo ""

read -p "Is this correct? (y/n): " CONFIRM
if [ "$CONFIRM" != "y" ]; then
    echo "Aborted."
    exit 1
fi

# Step 3: Create supervisor configurations
echo -e "${YELLOW}Step 3: Creating Supervisor configuration...${NC}"

cat > /etc/supervisor/conf.d/aidepos-queue-worker.conf <<EOF
[program:aidepos-queue-worker]
command=$PHP_PATH $APP_PATH/artisan queue:work database --timeout=10900 --tries=2 --sleep=3 --max-jobs=100 --max-time=3600
process_name=%(program_name)s_%(process_num)02d
numprocs=$NUM_PROCS
user=$WEB_USER
directory=$APP_PATH
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
priority=999
startsecs=10
stopwaitsecs=10920
stdout_logfile=$APP_PATH/storage/logs/queue-worker.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=5
stderr_logfile=$APP_PATH/storage/logs/queue-worker-error.log
stderr_logfile_maxbytes=50MB
stderr_logfile_backups=5
environment=PATH="/usr/local/bin:/usr/bin:/bin",HOME="$APP_PATH",USER="$WEB_USER"
EOF

echo -e "${GREEN}✓ Configuration file created${NC}"
echo ""

# Step 4: Create log directory if it doesn't exist
echo -e "${YELLOW}Step 4: Creating log directories...${NC}"
mkdir -p "$APP_PATH/storage/logs"
chown -R "$WEB_USER:$WEB_USER" "$APP_PATH/storage/logs"
echo -e "${GREEN}✓ Log directories ready${NC}"
echo ""

# Step 5: Reload Supervisor
echo -e "${YELLOW}Step 5: Reloading Supervisor...${NC}"
supervisorctl reread
supervisorctl update
echo -e "${GREEN}✓ Supervisor configuration reloaded${NC}"
echo ""

# Step 6: Start the workers
echo -e "${YELLOW}Step 6: Starting queue workers...${NC}"
supervisorctl start aidepos-queue-worker:*
echo -e "${GREEN}✓ Queue workers started${NC}"
echo ""

# Step 7: Check status
echo -e "${YELLOW}Step 7: Checking worker status...${NC}"
supervisorctl status aidepos-queue-worker:*
echo ""

# Final instructions
echo "=================================================="
echo -e "${GREEN}INSTALLATION COMPLETE!${NC}"
echo "=================================================="
echo ""
echo "Queue workers are now running with:"
echo "  - 3-hour timeout (10,900 seconds)"
echo "  - $NUM_PROCS worker process(es)"
echo "  - Auto-restart on failure"
echo "  - Proper memory management"
echo ""
echo "USEFUL COMMANDS:"
echo "  Check status:   sudo supervisorctl status"
echo "  Restart:        sudo supervisorctl restart aidepos-queue-worker:*"
echo "  Stop:           sudo supervisorctl stop aidepos-queue-worker:*"
echo "  Start:          sudo supervisorctl start aidepos-queue-worker:*"
echo "  View logs:      tail -f $APP_PATH/storage/logs/queue-worker.log"
echo "  View errors:    tail -f $APP_PATH/storage/logs/queue-worker-error.log"
echo ""
echo "MONITORING:"
echo "  Watch worker activity:"
echo "    watch -n 2 'sudo supervisorctl status aidepos-queue-worker:*'"
echo ""
echo "  Monitor queue jobs:"
echo "    watch -n 5 'cd $APP_PATH && $PHP_PATH artisan queue:monitor'"
echo ""
echo "Your sync jobs will now process without timeouts!"
echo "=================================================="
