#!/bin/bash
# CRM SITECONSEIL database backup script
# Runs every 30 minutes via cron

BACKUP_DIR="/var/backups/crm-siteconseil"
DATE=$(date +%Y%m%d_%H%M%S)
FILENAME="crm_siteconseil_${DATE}.sql.gz"
KEEP_DAYS=1

# Dump database via Docker
docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T db-master pg_dump -U {{ db_user | default('crm-siteconseil') }} {{ db_name | default('crm-siteconseil') }} | gzip > "${BACKUP_DIR}/${FILENAME}"

# Check if backup was created
if [ -f "${BACKUP_DIR}/${FILENAME}" ] && [ -s "${BACKUP_DIR}/${FILENAME}" ]; then
    echo "[$(date)] DB Backup OK: ${FILENAME} ($(du -h "${BACKUP_DIR}/${FILENAME}" | cut -f1))"
else
    echo "[$(date)] ERROR: DB Backup failed"
    exit 1
fi

# Backup uploads
UPLOADS_FILENAME="uploads_${DATE}.tar.gz"
tar -czf "${BACKUP_DIR}/${UPLOADS_FILENAME}" -C /var/www/crm-siteconseil/public uploads 2>/dev/null

if [ -f "${BACKUP_DIR}/${UPLOADS_FILENAME}" ]; then
    echo "[$(date)] Uploads Backup OK: ${UPLOADS_FILENAME} ($(du -h "${BACKUP_DIR}/${UPLOADS_FILENAME}" | cut -f1))"
else
    echo "[$(date)] WARNING: Uploads backup failed"
fi

# Remove backups older than KEEP_DAYS days
find "${BACKUP_DIR}" -name "crm_siteconseil_*.sql.gz" -mtime +${KEEP_DAYS} -delete
find "${BACKUP_DIR}" -name "uploads_*.tar.gz" -mtime +${KEEP_DAYS} -delete
echo "[$(date)] Cleaned backups older than ${KEEP_DAYS} days"
