#!/bin/bash

# Tender Management System - Production Deployment Script
# Run this script on your production server

set -e

echo "🚀 Starting Tender Management System Production Deployment..."

# Configuration
APP_DIR="/var/www/html/tender-management"
DB_NAME="tender_management"
DB_USER="tender_user"
BACKUP_DIR="/var/backups/tender-management"

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
if [[ $EUID -eq 0 ]]; then
   print_error "This script should not be run as root for security reasons"
   exit 1
fi

# Create backup directory
print_status "Creating backup directory..."
sudo mkdir -p $BACKUP_DIR
sudo chown $USER:$USER $BACKUP_DIR

# Backup existing database if it exists
print_status "Checking for existing database..."
if mysql -u $DB_USER -p -e "USE $DB_NAME;" 2>/dev/null; then
    print_warning "Existing database found. Creating backup..."
    mysqldump -u $DB_USER -p $DB_NAME > "$BACKUP_DIR/backup_$(date +%Y%m%d_%H%M%S).sql"
    print_status "Database backup created in $BACKUP_DIR"
fi

# Create application directory
print_status "Setting up application directory..."
sudo mkdir -p $APP_DIR
cd $APP_DIR

# Set proper ownership
sudo chown -R www-data:www-data $APP_DIR
sudo chmod -R 755 $APP_DIR

# Install PHP dependencies
print_status "Installing PHP dependencies..."
composer install --optimize-autoloader --no-dev --no-interaction

# Install Node.js dependencies and build assets
print_status "Building frontend assets..."
npm install --production
npm run build

# Set up environment file
print_status "Setting up environment configuration..."
if [ ! -f .env ]; then
    if [ -f .env.production ]; then
        cp .env.production .env
        print_status "Copied .env.production to .env"
    else
        print_error ".env.production file not found!"
        exit 1
    fi
fi

# Generate application key if needed
if ! grep -q "APP_KEY=base64:" .env; then
    print_status "Generating application key..."
    php artisan key:generate --force
fi

# Set proper permissions
print_status "Setting file permissions..."
sudo chown -R www-data:www-data $APP_DIR
sudo chmod -R 755 $APP_DIR
sudo chmod -R 775 $APP_DIR/storage
sudo chmod -R 775 $APP_DIR/bootstrap/cache

# Import database
print_status "Setting up database..."
if [ -f "tender_management_production.sql" ]; then
    print_status "Importing database from SQL file..."
    mysql -u $DB_USER -p $DB_NAME < tender_management_production.sql
    print_status "Database imported successfully"
else
    print_warning "SQL file not found. Running migrations instead..."
    php artisan migrate --force
    php artisan db:seed --force
fi

# Clear and cache configuration
print_status "Optimizing application..."
php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan view:clear

php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

# Set up queue worker (optional)
print_status "Setting up queue worker..."
sudo tee /etc/systemd/system/tender-queue.service > /dev/null <<EOF
[Unit]
Description=Tender Management Queue Worker
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=$APP_DIR
ExecStart=/usr/bin/php $APP_DIR/artisan queue:work --sleep=3 --tries=3 --max-time=3600
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable tender-queue
sudo systemctl start tender-queue

# Set up log rotation
print_status "Setting up log rotation..."
sudo tee /etc/logrotate.d/tender-management > /dev/null <<EOF
$APP_DIR/storage/logs/*.log {
    daily
    missingok
    rotate 14
    compress
    notifempty
    create 644 www-data www-data
    postrotate
        systemctl reload php8.2-fpm
    endscript
}
EOF

# Set up cron job for scheduled tasks
print_status "Setting up scheduled tasks..."
(crontab -l 2>/dev/null; echo "* * * * * cd $APP_DIR && php artisan schedule:run >> /dev/null 2>&1") | crontab -

# Create database backup script
print_status "Creating backup script..."
sudo tee /usr/local/bin/backup-tender-db > /dev/null <<EOF
#!/bin/bash
BACKUP_FILE="$BACKUP_DIR/tender_db_\$(date +%Y%m%d_%H%M%S).sql"
mysqldump -u $DB_USER -p$DB_PASSWORD $DB_NAME > \$BACKUP_FILE
gzip \$BACKUP_FILE
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
echo "Database backup completed: \$BACKUP_FILE.gz"
EOF

sudo chmod +x /usr/local/bin/backup-tender-db

# Add daily backup to cron
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/backup-tender-db") | crontab -

print_status "✅ Production deployment completed successfully!"
print_status ""
print_status "📋 Next Steps:"
print_status "1. Configure your web server (Nginx/Apache) to point to $APP_DIR/public"
print_status "2. Set up SSL certificate with Let's Encrypt"
print_status "3. Update .env file with your production settings"
print_status "4. Test the application thoroughly"
print_status "5. Set up monitoring and alerting"
print_status ""
print_status "📁 Important Files:"
print_status "- Application: $APP_DIR"
print_status "- Backups: $BACKUP_DIR"
print_status "- Logs: $APP_DIR/storage/logs"
print_status ""
print_status "🔧 Services:"
print_status "- Queue Worker: sudo systemctl status tender-queue"
print_status "- Database Backups: /usr/local/bin/backup-tender-db"
print_status ""
print_warning "⚠️  Remember to:"
print_warning "- Change default passwords"
print_warning "- Configure firewall rules"
print_warning "- Set up SSL certificates"
print_warning "- Test all functionality"

echo ""
echo "🎉 Tender Management System is ready for production!"
