#!/bin/sh
set -eu

echo "Building DevOps web and backend artifacts..."
cd /opt/bytelyst/learning_ai_devops_tools/dashboard/web && pnpm build
cd /opt/bytelyst/learning_ai_devops_tools/dashboard/backend && pnpm build

echo "Copying frontend assets into devops-web..."
docker cp web/.next devops-web:/app/web/.next

echo "Copying backend bundle into devops-backend..."
docker cp backend/dist devops-backend:/app/backend/dist

echo "Restarting devops-backend..."
docker restart devops-backend >/dev/null

echo "Waiting for backend readiness..."
for _ in 1 2 3 4 5 6 7 8 9 10; do
  READY_JSON="$(curl -s http://127.0.0.1:4004/health || true)"
  echo "$READY_JSON" | grep -q '"status":"ok"' && break
  sleep 2
done

echo "Restarting devops-web..."
docker restart devops-web >/dev/null

echo "Waiting for web readiness..."
for _ in 1 2 3 4 5 6 7 8 9 10; do
  if curl -s http://127.0.0.1:3049 > /dev/null; then
    break
  fi
  sleep 2
done

echo "DevOps Dashboard hotcopy deployment complete"
echo "Backend health:"
curl -s http://127.0.0.1:4004/health
echo ""
echo "Web status:"
curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:3049
