#!/bin/bash
set -e

echo "=== EduBox V2 Setup ==="

# Configure UFW
echo "Configuring firewall..."
if command -v ufw &> /dev/null; then
    ufw default deny incoming
    ufw default allow outgoing
    ufw allow 22/tcp
    ufw allow 1586/tcp
    ufw allow 80/tcp
    ufw allow 443/tcp
    ufw allow 3001/tcp
    ufw allow 41641/udp
    echo "UFW configured."
else
    echo "UFW not found, skipping firewall config."
fi

# Change SSH port
if [ -f /etc/ssh/sshd_config ]; then
    echo "Changing SSH port to 1586..."
    sed -i 's/^#\?Port .*/Port 1586/' /etc/ssh/sshd_config
    systemctl restart sshd || true
    echo "SSH port changed to 1586."
fi

# Generate .env if missing
if [ ! -f .env ]; then
    echo "Generating .env from .env.example..."
    cp .env.example .env
    echo "Please edit .env with your secure values before running docker compose."
else
    echo ".env already exists, skipping generation."
fi

# Build and start
echo "Building and starting services..."
docker compose up -d --build

echo ""
echo "=== Setup complete ==="
echo "Server:     http://localhost"
echo "Gitea:      http://localhost:3001"
echo "SSH port:   1586"
echo ""
echo "Don't forget to update .env with secure passwords!"
