#!/bin/bash
# /opt/rfcp/setup.sh

set -e

echo "🚀 RFCP Backend Setup"

# 1. Install system deps
echo "📦 Installing system packages..."
apt install -y python3.12-venv python3-pip

# 2. Backend setup
echo "🐍 Setting up Python backend..."
cd /opt/rfcp
mkdir -p backend/{app,tests}
mkdir -p data/terrain

# Create __init__.py
touch backend/app/__init__.py

# Create venv
cd backend
python3 -m venv venv
source venv/bin/activate

# Install deps
pip install fastapi uvicorn python-multipart aiofiles

# Create main.py (вже є в прикладі вище)

# 3. Frontend setup
echo "📱 Setting up frontend..."
cd /opt/rfcp/frontend
npm install

# 4. Build frontend for production
echo "🔨 Building frontend..."
npm run build

# 5. DNS setup
echo "🌐 Configuring DNS..."
if ! grep -q "rfcp.eliah.one" /etc/dnsmasq.d/matrix.conf; then
    echo "address=/rfcp.eliah.one/10.10.10.1" >> /etc/dnsmasq.d/matrix.conf
    systemctl restart dnsmasq
fi

# 6. Caddy config
echo "🔧 Configuring Caddy..."
if ! grep -q "rfcp.eliah.one" /etc/caddy/Caddyfile; then
    cat >> /etc/caddy/Caddyfile << 'CADDY_EOF'

rfcp.eliah.one {
    reverse_proxy localhost:3000
    reverse_proxy /api/* localhost:8090
}
CADDY_EOF
    systemctl reload caddy
fi

echo "✅ Setup complete!"
echo ""
echo "Next steps:"
echo "1. cd /opt/rfcp/backend && source venv/bin/activate"
echo "2. uvicorn app.main:app --host 0.0.0.0 --port 8090"
echo ""
echo "Or use Docker:"
echo "cd /opt/rfcp && docker compose up -d"
