#!/bin/bash

# Quick Deployment Script - Run from LOCAL machine
# This will upload files and deploy to the server automatically

set -e

SERVER_IP="37.60.249.71"
SERVER_USER="root"
APP_DIR="/opt/zerp"

echo "🚀 Starting Z.CRM Deployment to $SERVER_IP..."

# Upload files to server
echo "📤 Uploading files to server..."
rsync -avz --progress \
  --exclude 'node_modules' \
  --exclude '.git' \
  --exclude '.next' \
  --exclude 'dist' \
  --exclude '*.log' \
  --exclude '.DS_Store' \
  ./ $SERVER_USER@$SERVER_IP:$APP_DIR/

echo "📦 Files uploaded successfully!"

# SSH to server and run deployment
echo "🔨 Building and starting services on server..."
ssh $SERVER_USER@$SERVER_IP << 'ENDSSH'
cd /opt/zerp

# Install Docker if not present
if ! command -v docker &> /dev/null; then
    echo "Installing Docker..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh
    systemctl enable docker
    systemctl start docker
    rm get-docker.sh
fi

# Install Docker Compose if not present
if ! command -v docker-compose &> /dev/null; then
    echo "Installing Docker Compose..."
    curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
fi

# Create .env if it doesn't exist
if [ ! -f .env ]; then
    echo "Creating .env file..."
    cat > .env << 'EOF'
POSTGRES_PASSWORD=SecurePassword123!ChangeMe
JWT_SECRET=change-this-jwt-secret-to-something-secure-$(openssl rand -hex 32)
DOMAIN=zerp.atmata-group.com
EOF
    echo "⚠️  WARNING: Please update the .env file with secure passwords!"
fi

# Stop existing containers
echo "Stopping existing containers..."
docker-compose down || true

# Build and start services
echo "Building and starting services..."
docker-compose up -d --build

# Wait for services to be ready
echo "Waiting for services to start..."
sleep 10

# Show status
echo "Checking service status..."
docker-compose ps

echo ""
echo "✅ Deployment complete!"
echo ""
echo "Services are running:"
echo "  - Frontend: http://$SERVER_IP:3000"
echo "  - Backend API: http://$SERVER_IP:5001"
echo "  - Database: $SERVER_IP:5432"
echo ""
echo "View logs with:"
echo "  docker-compose logs -f"
echo ""
echo "⚠️  IMPORTANT: Configure Nginx Proxy Manager to point zerp.atmata-group.com to port 3000"
ENDSSH

echo ""
echo "🎉 Deployment successful!"
echo ""
echo "📋 Next Steps:"
echo "1. SSH to server: ssh root@37.60.249.71"
echo "2. Update .env file: nano /opt/zerp/.env"
echo "3. Configure Nginx Proxy Manager:"
echo "   - Domain: zerp.atmata-group.com"
echo "   - Forward to: localhost:3000"
echo "   - Enable SSL"
echo ""
