#!/bin/sh
if [ -z "$MARIADB_USER" ] || [ -z "$MARIADB_PASSWORD" ] || [ -z "$MARIADB_DATABASE" ]; then 
  echo "MARIADB_USER, MARIADB_PASSWORD and MARIADB_DATABASE must be set"
  exit 1
fi
if [ -z "$APP_NAME" ]; then
  echo "APP_NAME must be set"
  exit 1
fi
if [ -z "$BACKUP_RETENTION" ]; then
  echo "BACKUP_RETENTION must be set"
  exit 1
fi

echo "Creating backup of MariaDB database for app: $APP_NAME"
/usr/bin/mariadb-dump --single-transaction -h mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE | gzip > /backup/$APP_NAME-sql-`date +"%Y%m%d"`.sql.gz

BACKUP_FILE_PATTERN="$APP_NAME-sql-*.sql.gz"
echo "Removing old backups matching pattern: $BACKUP_FILE_PATTERN"
find /backup -type f -name "$BACKUP_FILE_PATTERN" -mtime +$BACKUP_RETENTION | xargs --no-run-if-empty rm
