#!/bin/bash
set -e

echo "=========================================="
echo "  AegisOne Documents Module Deploy"
echo "=========================================="

REMOTE="root@81.177.141.34"
REMOTE_DIR="/opt/projects/aegisone-py/app"

echo "[1/4] Копирование documents_router.py..."
scp app/documents_router.py $REMOTE:$REMOTE_DIR/
echo "  ✅ documents_router.py скопирован"

echo "[2/4] Копирование шаблонов документов..."
ssh $REMOTE "mkdir -p $REMOTE_DIR/templates/documents"
scp app/templates/documents/list.html $REMOTE:$REMOTE_DIR/templates/documents/
scp app/templates/documents/view.html $REMOTE:$REMOTE_DIR/templates/documents/
scp app/templates/documents/edit.html $REMOTE:$REMOTE_DIR/templates/documents/
scp app/templates/documents/permissions.html $REMOTE:$REMOTE_DIR/templates/documents/
echo "  ✅ Шаблоны скопированы"

echo "[3/4] Копирование docs и permissions..."
ssh $REMOTE "mkdir -p /opt/projects/aegisone-py/docs /opt/projects/aegisone-py/permissions"
scp -r docs/* $REMOTE:/opt/projects/aegisone-py/docs/
echo "  ✅ Документы скопированы"

echo "[4/4] Обновление main.py и перезапуск..."
scp app/main.py $REMOTE:$REMOTE_DIR/
scp app/services/docs_permissions.py $REMOTE:$REMOTE_DIR/services/

ssh $REMOTE "cd /opt/projects/aegisone-py && docker compose build --no-cache app && docker compose up -d app"
echo "  ✅ Приложение пересобрано и запущено"

echo ""
echo "=========================================="
echo "  Готово! Проверка..."
echo "=========================================="
sleep 5
ssh $REMOTE "curl -s -o /dev/null -w 'HTTP %{http_code}' http://localhost:8000/service/documents/"
echo ""
echo "URL: https://service.aegisone.ru/service/documents/"
