#!/bin/bash
set -e

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

# Check if running as root
if [ "$(id -u)" -eq 0 ]; then
    echo -e "${YELLOW}⚠ Warning: Running as root. It's recommended to run this script as a non-root user.${NC}"
    read -p "Continue as root? [y/N] " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Aborting...${NC}"
        exit 1
    fi
fi

# Check for required commands
for cmd in docker docker-compose; do
    if ! command -v $cmd &> /dev/null; then
        echo -e "${RED}✗ $cmd is not installed. Please install it and try again.${NC}"
        exit 1
    fi
done

# Load environment from .env.production if it exists
if [ -f ".env.production" ]; then
    echo -e "${GREEN}✓ Loading environment from .env.production${NC}"
    export $(grep -v '^#' .env.production | xargs)
else
    echo -e "${YELLOW}⚠ .env.production not found. Using default environment variables.${NC}"
fi

# Build and start services
echo -e "\n${GREEN}🚀 Starting production deployment...${NC}"

# Build and start the services
echo -e "\n${GREEN}🔨 Building and starting services...${NC}"
docker-compose -f docker-compose.yml up -d --build

# Show container status
echo -e "\n${GREEN}📊 Container status:${NC}"
docker-compose ps

# Show logs for a few seconds to check for errors
echo -e "\n${GREEN}📋 Tailing logs for 10 seconds (press Ctrl+C to continue)...${NC}
docker-compose logs --tail=20 -f & 
LOG_PID=$!
sleep 10
kill $LOG_PID 2>/dev/null

# Show completion message
echo -e "\n${GREEN}✅ Deployment complete!${NC}"
echo -e "\nYour application should now be running at: ${GREEN}http://localhost${NC}"
echo -e "\nUseful commands:"
echo -e "  ${YELLOW}docker-compose logs -f${NC}     - View logs"
echo -e "  ${YELLOW}docker-compose down${NC}        - Stop all services"
echo -e "  ${YELLOW}docker-compose ps${NC}          - Check container status"
echo -e "  ${YELLOW}docker-compose exec backend [cmd]${NC} - Run command in backend container"
echo -e "  ${YELLOW}docker-compose exec ui [cmd]${NC}      - Run command in UI container"
echo -e "\nTo update the application, run this script again after making your changes.\n"

exit 0
