#!/bin/bash

# Mercado Marketing Operator - Production Server Setup Script
# This script configures Supervisor for Queues and Cron for the Scheduler.
# Run this script on your Ubuntu/Debian production server as root.

echo "============================================================"
echo " Mercado Phase 7: Production Readiness Setup"
echo "============================================================"

# Ensure script is run as root
if [ "$EUID" -ne 0 ]
  then echo "Please run as root (sudo ./setup-production.sh)"
  exit
fi

APP_DIR=$(pwd)
USER="www-data" # Change this if your web server user is different

echo "1. Installing Supervisor..."
apt-get update
apt-get install -y supervisor

echo "2. Configuring Supervisor for Mercado Queues..."
cat > /etc/supervisor/conf.d/mercado-worker.conf <<EOF
[program:mercado-worker]
process_name=%(program_name)s_%(process_num)02d
command=php ${APP_DIR}/artisan queue:work --queue=attribution,default --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=$USER
numprocs=2
redirect_stderr=true
stdout_logfile=${APP_DIR}/storage/logs/worker.log
stopwaitsecs=3600
EOF

echo "Reloading Supervisor..."
supervisorctl reread
supervisorctl update
supervisorctl start mercado-worker:*

echo "3. Configuring Cron Job for Laravel Scheduler..."
CRON_JOB="* * * * * cd ${APP_DIR} && php artisan schedule:run >> /dev/null 2>&1"
(crontab -u $USER -l 2>/dev/null | grep -v "artisan schedule:run"; echo "$CRON_JOB") | crontab -u $USER -

echo "============================================================"
echo " Setup Complete!"
echo " - Supervisor is now managing your queue workers (2 processes)."
echo " - Cron is now triggering the Laravel Scheduler every minute."
echo " - You can view worker logs at: storage/logs/worker.log"
echo "============================================================"
