#!/bin/sh
set -e
DATE=$(date +"%Y%m%d-%H%M%S")
BACKUP_DIR=/backups
FILE="$BACKUP_DIR/dms_db_$DATE.sql.gz"
mkdir -p "$BACKUP_DIR"

mysqldump -h dms_mariadb -u"${MARIADB_USER:-center}" -p"${MARIADB_PASSWORD:-Center2025}" --databases "${MARIADB_DB:-dms_db}" \
  --single-transaction --triggers --routines --events \
  | gzip -c > "$FILE"

if [ ! -s "$FILE" ]; then
  echo "Backup failed: empty file" >&2
  exit 1
fi

find "$BACKUP_DIR" -type f -name 'dms_db_*.sql.gz' -mtime +14 -delete