#!/bin/bash
# ============================================================
# Automated PostgreSQL Backup Script
# Run daily via cron: 0 2 * * * /opt/turf-saas/infra/scripts/backup_db.sh
# ============================================================

set -euo pipefail

BACKUP_DIR="${BACKUP_DIR:-/opt/backups/turf-saas}"
KEEP_DAYS="${KEEP_DAYS:-30}"
DB_NAME="${POSTGRES_DB:-turf_saas}"
DB_USER="${POSTGRES_USER:-turf}"
DB_HOST="${POSTGRES_HOST:-postgres}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/turf_saas_${TIMESTAMP}.sql.gz"

echo "[$(date -Iseconds)] Starting backup: ${BACKUP_FILE}"

# Ensure backup directory exists
mkdir -p "${BACKUP_DIR}"

# Perform backup
PGPASSWORD="${POSTGRES_PASSWORD}" pg_dump \
    -h "${DB_HOST}" \
    -U "${DB_USER}" \
    -d "${DB_NAME}" \
    --no-owner \
    --no-acl \
    | gzip > "${BACKUP_FILE}"

SIZE=$(du -sh "${BACKUP_FILE}" | cut -f1)
echo "[$(date -Iseconds)] Backup complete: ${BACKUP_FILE} (${SIZE})"

# Remove backups older than KEEP_DAYS
find "${BACKUP_DIR}" -name "turf_saas_*.sql.gz" -mtime "+${KEEP_DAYS}" -delete
echo "[$(date -Iseconds)] Old backups cleaned (kept last ${KEEP_DAYS} days)"

# Optional: notify on completion
if [ -n "${TELEGRAM_BOT_TOKEN:-}" ] && [ -n "${TELEGRAM_CHAT_ID:-}" ]; then
    curl -s -X POST \
        "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
        -d chat_id="${TELEGRAM_CHAT_ID}" \
        -d text="✅ DB Backup OK: turf_saas ${TIMESTAMP} (${SIZE})" \
        > /dev/null || true
fi
