#!/bin/bash

# Complete deployment script for Church Music Database
# Installs systemd services and sets up SSL with Nginx

set -e

PROJECT_DIR="/media/pts/Website/Church_HOP_MusicData/new-site"
DOMAIN="houseofprayer.ddns.net"

echo "🚀 Church Music Database - Complete Deployment"
echo "================================================"

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Please run as root: sudo $0"
    exit 1
fi

# Step 1: Install systemd services
echo ""
echo "📦 Installing systemd services..."

# Backend service
cp "$PROJECT_DIR/church-music-backend.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable church-music-backend.service
echo "✅ Backend service installed"

# Frontend service
cp "$PROJECT_DIR/church-music-frontend.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable church-music-frontend.service
echo "✅ Frontend service installed"

# Step 2: Start services
echo ""
echo "🔄 Starting services..."
systemctl restart church-music-backend.service
systemctl restart church-music-frontend.service

sleep 3

# Check service status
echo ""
echo "📊 Service Status:"
echo "Backend:"
systemctl status church-music-backend.service --no-pager | grep -E "Active:|Loaded:" || true
echo ""
echo "Frontend:"
systemctl status church-music-frontend.service --no-pager | grep -E "Active:|Loaded:" || true

# Step 3: Verify ports are listening
echo ""
echo "🔍 Verifying ports..."
if lsof -i:8080 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "✅ Backend listening on port 8080"
else
    echo "❌ Backend not listening on port 8080"
fi

if lsof -i:5100 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "✅ Frontend listening on port 5100"
else
    echo "❌ Frontend not listening on port 5100"
fi

# Step 4: Setup SSL and Nginx
echo ""
echo "🔐 Setting up SSL and Nginx..."
bash "$PROJECT_DIR/setup-ssl.sh"

echo ""
echo "================================================"
echo "✨ Deployment Complete!"
echo "================================================"
echo ""
echo "🌐 Your site is now available at:"
echo "   https://$DOMAIN"
echo ""
echo "🔧 Manage services:"
echo "   Backend:  sudo systemctl {start|stop|restart|status} church-music-backend"
echo "   Frontend: sudo systemctl {start|stop|restart|status} church-music-frontend"
echo "   Nginx:    sudo systemctl {start|stop|restart|status} nginx"
echo ""
echo "📝 View logs:"
echo "   Backend:  sudo journalctl -u church-music-backend -f"
echo "   Frontend: sudo journalctl -u church-music-frontend -f"
echo "   Nginx:    sudo tail -f /var/log/nginx/church-music-*.log"
echo ""
echo "🔄 Services will automatically start on system boot"
echo ""
