#!/bin/bash
# גיבוי יומי אוטומטי למסד הנתונים PostgreSQL
# Usage: ./backup-db.sh [backup_dir]
# Cron: 0 2 * * * /home/chaim/legal-ai/scripts/backup-db.sh

set -euo pipefail

BACKUP_DIR="${1:-/home/chaim/legal-ai/data/backups}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/legal_ai_${TIMESTAMP}.sql.gz"

# Load DB credentials from .env
source "${HOME}/.env" 2>/dev/null || true

DB_HOST="${POSTGRES_HOST:-127.0.0.1}"
DB_PORT="${POSTGRES_PORT:-5433}"
DB_NAME="${POSTGRES_DB:-legal_ai}"
DB_USER="${POSTGRES_USER:-legal_ai}"

# Create backup directory
mkdir -p "${BACKUP_DIR}"

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

# Dump and compress
PGPASSWORD="${POSTGRES_PASSWORD:-}" pg_dump \
    -h "${DB_HOST}" \
    -p "${DB_PORT}" \
    -U "${DB_USER}" \
    -d "${DB_NAME}" \
    --format=custom \
    --compress=9 \
    -f "${BACKUP_FILE%.gz}"

gzip "${BACKUP_FILE%.gz}" 2>/dev/null || true

echo "[$(date)] Backup completed: ${BACKUP_FILE}"

# Verify backup
if [ -f "${BACKUP_FILE}" ]; then
    SIZE=$(du -h "${BACKUP_FILE}" | cut -f1)
    echo "[$(date)] Backup size: ${SIZE}"
else
    # pg_dump --format=custom already compresses
    BACKUP_FILE="${BACKUP_FILE%.gz}"
    SIZE=$(du -h "${BACKUP_FILE}" | cut -f1)
    echo "[$(date)] Backup size: ${SIZE} (custom format)"
fi

# Cleanup: keep last 30 days
find "${BACKUP_DIR}" -name "legal_ai_*.sql*" -mtime +30 -delete 2>/dev/null
echo "[$(date)] Old backups cleaned (>30 days)"

# Count remaining backups
COUNT=$(find "${BACKUP_DIR}" -name "legal_ai_*" | wc -l)
echo "[$(date)] Total backups: ${COUNT}"
