#!/bin/bash
set -e

BACKUP_DIR="/backup/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

echo "=== Homelab Backup ==="
echo "Backup directory: $BACKUP_DIR"

# Backup PostgreSQL databases
echo "[1/4] Backing up PostgreSQL databases..."
sudo -u postgres pg_dump mattermost > "$BACKUP_DIR/mattermost.sql"
sudo -u postgres pg_dump synapse > "$BACKUP_DIR/synapse.sql"
sudo -u postgres pg_dump mastodon_production > "$BACKUP_DIR/mastodon.sql"

# Backup Mastodon media
echo "[2/4] Backing up Mastodon media..."
tar -czf "$BACKUP_DIR/mastodon_media.tar.gz" -C /opt/mastodon public/system 2>/dev/null || true

# Backup Mattermost data
echo "[3/4] Backing up Mattermost data..."
tar -czf "$BACKUP_DIR/mattermost_data.tar.gz" -C /opt/mattermost data config 2>/dev/null || true

# Backup Matrix/Synapse
echo "[4/4] Backing up Matrix data..."
tar -czf "$BACKUP_DIR/synapse_data.tar.gz" -C /opt synapse 2>/dev/null || true

echo ""
echo "Backup complete: $BACKUP_DIR"
ls -lh "$BACKUP_DIR"
