#!/bin/bash
set -e

echo "========================================="
echo "Deploying Normogen to Solaria"
echo "========================================="

# Server details
SERVER="alvaro@solaria"
REMOTE_DIR="/home/alvaro/normogen"
REPO_URL="ssh://git@gitea.solivarez.com.ar/alvaro/normogen.git"

echo ""
echo "Step 1: Pushing latest changes to git..."
git push origin main

echo ""
echo "Step 2: Connecting to Solaria..."
ssh $SERVER << 'ENDSSH'
set -e

echo "Creating directory if not exists..."
mkdir -p ~/normogen

cd ~/normogen

if [ -d ".git" ]; then
    echo "Pulling latest changes..."
    git pull origin main
else
    echo "Cloning repository..."
    git clone $REPO_URL .
fi

cd backend

echo ""
echo "Step 3: Stopping existing containers..."
docker-compose down || true

echo ""
echo "Step 4: Building and starting new containers..."
docker-compose up -d --build

echo ""
echo "Step 5: Waiting for services to be healthy..."
sleep 5

echo ""
echo "Step 6: Checking container status..."
docker-compose ps

echo ""
echo "Step 7: Checking backend logs..."
docker-compose logs backend | tail -20

ENDSSH

echo ""
echo "========================================="
echo "Deployment complete!"
echo "========================================="
echo ""
echo "API is available at: http://solaria:8000"
echo "Health check: http://solaria:8000/health"
echo ""
