#!/bin/bash
#
# Restart all PLAGIS services (Backend API and Frontend Next.js)
#

set -e

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Restarting All PLAGIS Services${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${YELLOW}⚠️  Running without sudo - some operations may fail${NC}"
    echo -e "${YELLOW}   For full functionality, run: sudo bash restart_all_services.sh${NC}"
    echo ""
    USE_SUDO=""
else
    USE_SUDO=""
fi

# Service names
API_SERVICE="plagis-aumentum-api"
NEXTJS_SERVICE="plagis-nextjs"
MOUNT_SERVICE="ensure-contentstore-mount.service"
MOUNT_UNIT="mnt-aumentum_contentstore.mount"

# Function to check service status
check_service() {
    local service=$1
    if systemctl is-active --quiet "$service" 2>/dev/null; then
        echo -e "${GREEN}✓${NC} $service is running"
        return 0
    else
        echo -e "${RED}✗${NC} $service is not running"
        return 1
    fi
}

# Function to restart service
restart_service() {
    local service=$1
    local description=$2
    
    echo -e "${YELLOW}Restarting $description...${NC}"
    
    if systemctl list-unit-files | grep -q "$service"; then
        $USE_SUDO systemctl restart "$service" 2>/dev/null || {
            echo -e "${RED}Failed to restart $service${NC}"
            return 1
        }
        
        # Wait a moment and check status
        sleep 2
        if check_service "$service"; then
            echo -e "${GREEN}✓ $description restarted successfully${NC}"
            return 0
        else
            echo -e "${RED}✗ $description failed to start${NC}"
            return 1
        fi
    else
        echo -e "${YELLOW}⚠️  Service $service not found (may not be installed)${NC}"
        return 1
    fi
}

# Check current status
echo -e "${BLUE}Current Service Status:${NC}"
check_service "$API_SERVICE" || true
check_service "$NEXTJS_SERVICE" || true
check_service "$MOUNT_SERVICE" || true
echo ""

# Restart services in order
echo -e "${BLUE}Restarting Services...${NC}"
echo ""

# 1. Ensure mount is active first
if systemctl list-unit-files | grep -q "$MOUNT_SERVICE"; then
    echo -e "${YELLOW}[1/3] Ensuring contentstore mount...${NC}"
    $USE_SUDO systemctl start "$MOUNT_SERVICE" 2>/dev/null || true
    sleep 1
    if mountpoint -q /mnt/aumentum_contentstore 2>/dev/null; then
        echo -e "${GREEN}✓ Contentstore is mounted${NC}"
    else
        echo -e "${YELLOW}⚠️  Contentstore mount check skipped (may need manual mount)${NC}"
    fi
    echo ""
fi

# 2. Restart API service
if systemctl list-unit-files | grep -q "$API_SERVICE"; then
    restart_service "$API_SERVICE" "Backend API"
    echo ""
else
    echo -e "${YELLOW}⚠️  API service not found${NC}"
    echo ""
fi

# 3. Restart Next.js service
if systemctl list-unit-files | grep -q "$NEXTJS_SERVICE"; then
    restart_service "$NEXTJS_SERVICE" "Frontend Next.js"
    echo ""
else
    echo -e "${YELLOW}⚠️  Next.js service not found${NC}"
    echo ""
fi

# Final status check
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Final Service Status:${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

API_STATUS=$(systemctl is-active "$API_SERVICE" 2>/dev/null || echo "inactive")
NEXTJS_STATUS=$(systemctl is-active "$NEXTJS_SERVICE" 2>/dev/null || echo "inactive")

if [ "$API_STATUS" = "active" ]; then
    echo -e "${GREEN}✓ Backend API: RUNNING${NC}"
else
    echo -e "${RED}✗ Backend API: NOT RUNNING${NC}"
fi

if [ "$NEXTJS_STATUS" = "active" ]; then
    echo -e "${GREEN}✓ Frontend Next.js: RUNNING${NC}"
else
    echo -e "${RED}✗ Frontend Next.js: NOT RUNNING${NC}"
fi

echo ""

# Show service details
if [ "$API_STATUS" = "active" ]; then
    echo -e "${BLUE}API Service Details:${NC}"
    $USE_SUDO systemctl status "$API_SERVICE" --no-pager -l | head -5 | sed 's/^/  /' || true
    echo ""
fi

if [ "$NEXTJS_STATUS" = "active" ]; then
    echo -e "${BLUE}Next.js Service Details:${NC}"
    $USE_SUDO systemctl status "$NEXTJS_SERVICE" --no-pager -l | head -5 | sed 's/^/  /' || true
    echo ""
fi

# Summary
if [ "$API_STATUS" = "active" ] && [ "$NEXTJS_STATUS" = "active" ]; then
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}✅ All services restarted successfully!${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo "Services are now running:"
    echo "  • Backend API: http://localhost:8001"
    echo "  • Frontend Next.js: http://localhost:3000"
    echo "  • Via Nginx: http://10.10.10.127:7000"
    echo ""
    echo "View logs:"
    echo "  • API: sudo tail -f /var/log/plagis/api.log"
    echo "  • Next.js: sudo tail -f /var/log/plagis/nextjs.log"
    exit 0
else
    echo -e "${RED}========================================${NC}"
    echo -e "${RED}⚠️  Some services failed to start${NC}"
    echo -e "${RED}========================================${NC}"
    echo ""
    echo "Troubleshooting:"
    echo "  • Check service status: sudo systemctl status <service-name>"
    echo "  • View logs: sudo journalctl -u <service-name> -n 50"
    echo "  • Check errors: sudo journalctl -u <service-name> -p err -n 20"
    exit 1
fi

