#!/bin/bash
# Production Deployment Script for Church Music System
# This script will set up auto-start services and optimize for production

set -e

echo "🚀 Starting production deployment..."

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

PROJECT_DIR="/media/pts/Website/Church_HOP_MusicData"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"

# Step 1: Stop current development servers
echo -e "${BLUE}[1/7] Stopping development servers...${NC}"
pkill -f "python.*app.py" 2>/dev/null || true
pkill -f "node.*react-scripts" 2>/dev/null || true
sleep 2

# Step 2: Build production frontend
echo -e "${BLUE}[2/7] Building production React frontend...${NC}"
cd $FRONTEND_DIR
export NODE_OPTIONS=--max-old-space-size=2048
npm run build || {
    echo -e "${RED}Frontend build failed. Check for syntax errors.${NC}"
    exit 1
}

# Step 3: Install systemd service for backend
echo -e "${BLUE}[3/7] Installing backend systemd service...${NC}"
sudo cp /tmp/church-music-backend.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable church-music-backend.service
sudo systemctl restart church-music-backend.service

# Step 4: Install Nginx configuration
echo -e "${BLUE}[4/7] Installing Nginx configuration...${NC}"
sudo apt-get install -y nginx 2>/dev/null || true
sudo cp /tmp/church-music-nginx.conf /etc/nginx/sites-available/church-music
sudo ln -sf /etc/nginx/sites-available/church-music /etc/nginx/sites-enabled/
sudo nginx -t || {
    echo -e "${RED}Nginx configuration test failed${NC}"
    exit 1
}

# Step 5: Start/restart services
echo -e "${BLUE}[5/7] Starting services...${NC}"
sudo systemctl enable nginx
sudo systemctl restart nginx
sudo systemctl status church-music-backend.service --no-pager || true

# Step 6: Verify PostgreSQL data
echo -e "${BLUE}[6/7] Verifying PostgreSQL connection...${NC}"
cd $BACKEND_DIR
source venv/bin/activate
python -c "from postgresql_models import SessionLocal; s = SessionLocal(); print('✅ PostgreSQL connected'); s.close()" || {
    echo -e "${RED}PostgreSQL connection failed${NC}"
    exit 1
}

# Step 7: Display status
echo -e "${BLUE}[7/7] Deployment complete!${NC}"
echo ""
echo -e "${GREEN}✅ Production services are running:${NC}"
echo "   • Backend: sudo systemctl status church-music-backend"
echo "   • Frontend: sudo systemctl status nginx"
echo ""
echo -e "${GREEN}✅ Access your site:${NC}"
echo "   • Local: http://localhost:3000"
echo "   • Network: http://192.168.10.130:3000"
echo "   • External: http://houseofprayer.ddns.net:3000"
echo ""
echo -e "${GREEN}✅ Services will auto-start on system restart${NC}"
echo ""
echo -e "${GREEN}✅ Resource optimized for shared server:${NC}"
echo "   • Backend: 512MB RAM, 50% CPU"
echo "   • Nginx: Gzip enabled, caching configured"
echo ""
echo "Logs:"
echo "   • Backend: $BACKEND_DIR/logs/"
echo "   • Nginx: /var/log/nginx/church-music-*.log"
