#!/bin/bash
# AutonetSellCar Staging Deployment Script
# This script is executed automatically by git post-receive hook

set -e

STAGING_DIR="/opt/autonet/staging"
LOG_FILE="/opt/autonet/logs/staging-deploy.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

mkdir -p /opt/autonet/logs

log "=========================================="
log "Starting Staging Deployment"
log "=========================================="

cd $STAGING_DIR

log "[1/4] Stopping existing containers..."
docker compose -f docker-compose.staging.yml down 2>/dev/null || true

log "[2/4] Building containers (this may take a while)..."
docker compose -f docker-compose.staging.yml build --no-cache

log "[3/4] Starting containers..."
docker compose -f docker-compose.staging.yml up -d

log "[4/4] Waiting for services to be ready..."
sleep 15

# Health check
BACKEND_OK=false
FRONTEND_OK=false

for i in {1..5}; do
    if curl -sf http://localhost:8001/docs > /dev/null 2>&1; then
        BACKEND_OK=true
        break
    fi
    log "Backend not ready yet, retry $i/5..."
    sleep 5
done

for i in {1..5}; do
    if curl -sf http://localhost:3001 > /dev/null 2>&1; then
        FRONTEND_OK=true
        break
    fi
    log "Frontend not ready yet, retry $i/5..."
    sleep 5
done

if $BACKEND_OK && $FRONTEND_OK; then
    log "=========================================="
    log "Staging Deployment SUCCESSFUL!"
    log "Frontend: http://192.168.0.202:3001"
    log "Backend:  http://192.168.0.202:8001/docs"
    log "=========================================="
    exit 0
else
    log "=========================================="
    log "Staging Deployment FAILED!"
    log "Backend: $BACKEND_OK, Frontend: $FRONTEND_OK"
    log "Check logs: docker compose -f docker-compose.staging.yml logs"
    log "=========================================="
    exit 1
fi
