#!/bin/bash
set -e

echo "=== Ubuntu VM Homelab Setup ==="
echo "This script sets up Mastodon, Mattermost, and Matrix/Element"

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Please run as root (sudo ./setup.sh)"
    exit 1
fi

# Update system
echo "[1/8] Updating system..."
apt-get update && apt-get upgrade -y

# Install dependencies
echo "[2/8] Installing dependencies..."
apt-get install -y \
    docker.io docker-compose-v2 \
    nginx \
    postgresql postgresql-contrib \
    curl wget git

# Start services
echo "[3/8] Starting services..."
systemctl enable --now docker
systemctl enable --now postgresql
systemctl enable --now nginx

# Setup PostgreSQL
echo "[4/8] Setting up PostgreSQL..."
sudo -u postgres psql -c "CREATE USER mmuser WITH PASSWORD 'REDACTED_PASSWORD';" 2>/dev/null || true
sudo -u postgres psql -c "CREATE DATABASE mattermost OWNER mmuser;" 2>/dev/null || true
sudo -u postgres psql -c "CREATE USER synapse WITH PASSWORD 'REDACTED_PASSWORD';" 2>/dev/null || true
sudo -u postgres psql -c "CREATE DATABASE synapse OWNER synapse ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' template=template0;" 2>/dev/null || true
sudo -u postgres psql -c "CREATE USER mastodon WITH PASSWORD 'REDACTED_PASSWORD' CREATEDB;" 2>/dev/null || true
sudo -u postgres psql -c "CREATE DATABASE mastodon_production OWNER mastodon;" 2>/dev/null || true

# Configure PostgreSQL for Docker access
echo "[5/8] Configuring PostgreSQL..."
echo "host    all             all             172.17.0.0/16           md5" >> /etc/postgresql/*/main/pg_hba.conf
echo "host    all             all             0.0.0.0/0               md5" >> /etc/postgresql/*/main/pg_hba.conf
sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" /etc/postgresql/*/main/postgresql.conf
systemctl restart postgresql

# Setup directories
echo "[6/8] Creating directories..."
mkdir -p /opt/mastodon /opt/mattermost /opt/synapse /opt/element/web

# Copy nginx configs
echo "[7/8] Setting up Nginx..."
cp nginx/*.conf /etc/nginx/sites-available/
ln -sf /etc/nginx/sites-available/mastodon.conf /etc/nginx/sites-enabled/
ln -sf /etc/nginx/sites-available/mattermost.conf /etc/nginx/sites-enabled/
ln -sf /etc/nginx/sites-available/matrix.conf /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx

echo "[8/8] Setup complete!"
echo ""
echo "Next steps:"
echo "1. Copy docker-compose files to /opt directories"
echo "2. Configure environment files with actual secrets"
echo "3. Run migrations and start services"
echo ""
echo "Ports:"
echo "  - Mastodon: 8082"
echo "  - Mattermost: 8081"
echo "  - Matrix/Element: 8080"
