#!/bin/bash
# ===========================================
# Business Platform Deployment Script
# ===========================================
# Usage: ./deploy.sh [command]
# Commands: setup, deploy, ssl, restart, logs, backup

set -e

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

# Configuration
PROJECT_DIR="/root/backend-bussiness"
DOMAIN="your-domain.com"  # CHANGE THIS to your domain

print_header() {
    echo -e "${BLUE}============================================${NC}"
    echo -e "${BLUE}  $1${NC}"
    echo -e "${BLUE}============================================${NC}"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

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

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

# Initial server setup
setup_server() {
    print_header "Setting up VPS Server"

    echo "Updating system packages..."
    apt-get update && apt-get upgrade -y

    echo "Installing Docker..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh
    rm get-docker.sh

    echo "Installing Docker Compose..."
    apt-get install -y docker-compose-plugin

    echo "Starting Docker service..."
    systemctl start docker
    systemctl enable docker

    echo "Installing additional tools..."
    apt-get install -y git curl wget htop ufw

    echo "Configuring firewall..."
    ufw allow ssh
    ufw allow http
    ufw allow https
    ufw --force enable

    print_success "Server setup complete!"
}

# Deploy the application
deploy() {
    print_header "Deploying Application"

    cd $PROJECT_DIR

    # Check if .env.prod exists
    if [ ! -f .env.prod ]; then
        print_error ".env.prod file not found!"
        print_warning "Please copy .env.prod.example to .env.prod and configure it"
        exit 1
    fi

    # Use initial nginx config if SSL not set up
    if [ ! -d "certbot/conf/live" ]; then
        print_warning "SSL not configured. Using HTTP-only nginx config."
        cp nginx/conf.d/default-initial.conf nginx/conf.d/default.conf
    fi

    echo "Stopping existing containers..."
    docker compose -f docker-compose.prod.yml down || true

    echo "Building new images..."
    docker compose -f docker-compose.prod.yml build --no-cache

    echo "Starting containers..."
    docker compose -f docker-compose.prod.yml up -d

    echo "Waiting for services to start..."
    sleep 15

    echo "Checking container status..."
    docker compose -f docker-compose.prod.yml ps

    print_success "Deployment complete!"
    echo ""
    echo "Your application should be available at:"
    echo "  - http://$DOMAIN (or https:// if SSL configured)"
}

# Setup SSL with Let's Encrypt
setup_ssl() {
    print_header "Setting up SSL Certificate"

    cd $PROJECT_DIR

    # Create certbot directories
    mkdir -p certbot/conf certbot/www

    # Get certificate
    echo "Obtaining SSL certificate for $DOMAIN..."
    docker compose -f docker-compose.prod.yml run --rm certbot certonly \
        --webroot \
        --webroot-path=/var/www/certbot \
        -d $DOMAIN \
        -d www.$DOMAIN \
        --email admin@$DOMAIN \
        --agree-tos \
        --no-eff-email

    if [ $? -eq 0 ]; then
        print_success "SSL certificate obtained!"

        # Update nginx config with SSL
        echo "Updating nginx configuration for SSL..."
        sed -i "s/your-domain.com/$DOMAIN/g" nginx/conf.d/default.conf

        # Restart nginx
        docker compose -f docker-compose.prod.yml restart nginx

        print_success "SSL setup complete!"
        echo "Your site is now available at https://$DOMAIN"
    else
        print_error "Failed to obtain SSL certificate"
        exit 1
    fi
}

# Restart services
restart() {
    print_header "Restarting Services"
    cd $PROJECT_DIR
    docker compose -f docker-compose.prod.yml restart
    print_success "Services restarted!"
}

# View logs
logs() {
    print_header "Application Logs"
    cd $PROJECT_DIR
    docker compose -f docker-compose.prod.yml logs -f --tail=100
}

# Backup database
backup() {
    print_header "Backing up Database"
    cd $PROJECT_DIR

    BACKUP_DIR="$PROJECT_DIR/backups"
    mkdir -p $BACKUP_DIR

    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    BACKUP_FILE="$BACKUP_DIR/mongodb_backup_$TIMESTAMP.gz"

    echo "Creating MongoDB backup..."
    docker compose -f docker-compose.prod.yml exec -T mongodb mongodump \
        --archive --gzip > $BACKUP_FILE

    print_success "Backup saved to: $BACKUP_FILE"
}

# Update application
update() {
    print_header "Updating Application"
    cd $PROJECT_DIR

    echo "Pulling latest changes..."
    git pull origin main

    echo "Rebuilding and restarting..."
    docker compose -f docker-compose.prod.yml up -d --build

    print_success "Update complete!"
}

# Show help
show_help() {
    echo "Usage: ./deploy.sh [command]"
    echo ""
    echo "Commands:"
    echo "  setup    - Initial server setup (install Docker, firewall, etc.)"
    echo "  deploy   - Deploy/redeploy the application"
    echo "  ssl      - Setup SSL certificate with Let's Encrypt"
    echo "  restart  - Restart all services"
    echo "  logs     - View application logs"
    echo "  backup   - Backup MongoDB database"
    echo "  update   - Pull latest code and redeploy"
    echo "  help     - Show this help message"
}

# Main script
case "$1" in
    setup)
        setup_server
        ;;
    deploy)
        deploy
        ;;
    ssl)
        setup_ssl
        ;;
    restart)
        restart
        ;;
    logs)
        logs
        ;;
    backup)
        backup
        ;;
    update)
        update
        ;;
    help|*)
        show_help
        ;;
esac
