#!/bin/bash

# Remote Setup Script - Runs ON THE SERVER

set -e

cd /opt/zerp

echo "🔧 Installing prerequisites..."

# 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
else
    echo "✓ Docker already installed"
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
else
    echo "✓ Docker Compose already installed"
fi

# Create .env if it doesn't exist
if [ ! -f .env ]; then
    echo "📝 Creating .env file..."
    RANDOM_JWT=$(openssl rand -hex 32)
    cat > .env << EOF
POSTGRES_PASSWORD=SecurePassword123!ChangeMe
JWT_SECRET=jwt-secret-${RANDOM_JWT}
DOMAIN=zerp.atmata-group.com
EOF
    echo "⚠️  Created .env file with default values. Please update with secure passwords!"
else
    echo "✓ .env file already exists"
fi

# Stop existing containers
echo "🛑 Stopping existing containers..."
docker-compose down 2>/dev/null || true

# Build and start services
echo "🔨 Building and starting services (this may take several minutes)..."
docker-compose up -d --build

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

# Show status
echo "📊 Service status:"
docker-compose ps

echo ""
echo "✅ Deployment complete!"
echo ""
echo "🌐 Services are accessible at:"
echo "  - Frontend: http://$(hostname -I | awk '{print $1}'):3000"
echo "  - Backend API: http://$(hostname -I | awk '{print $1}'):5001"
echo ""
echo "📋 View logs:"
echo "  docker-compose logs -f"
echo ""
echo "⚠️  NEXT STEPS:"
echo "1. Update .env file: nano /opt/zerp/.env"
echo "2. Restart services: docker-compose restart"
echo "3. Configure Nginx Proxy Manager:"
echo "   - Domain: zerp.atmata-group.com"
echo "   - Forward to: localhost:3000"
echo "   - Enable SSL with Let's Encrypt"
echo ""
