#!/bin/bash
# ============================================================
# AFINET — MySQL backup script (same-server, local storage)
# Runs inside the backup container every 6 hours.
# Keeps 7 days of backups (~28 files max).
# ============================================================

BACKUP_DIR="/backups"
KEEP_DAYS=7
INTERVAL=21600   # 6 hours in seconds
MYSQL_OPTS_FILE="/tmp/.mylogin.cnf"

echo "[$(date)] Backup service started. Interval: every 6 hours."

# Write credentials to a MySQL options file to avoid shell escaping issues
# with special characters in passwords
cat > "$MYSQL_OPTS_FILE" <<EOF
[client]
host=${DB_HOST}
user=${DB_USERNAME}
password=${DB_PASSWORD}
EOF
chmod 600 "$MYSQL_OPTS_FILE"

# Wait for MySQL to be ready before first backup
until mysqladmin --defaults-file="$MYSQL_OPTS_FILE" ping --silent 2>/dev/null; do
  echo "[$(date)] Waiting for MySQL to be ready..."
  sleep 5
done

echo "[$(date)] MySQL is ready."

while true; do
  TIMESTAMP=$(date +%Y%m%d_%H%M%S)
  FILE="${BACKUP_DIR}/afinet_${TIMESTAMP}.sql.gz"

  echo "[$(date)] Starting backup → ${FILE}"

  mysqldump \
    --defaults-file="$MYSQL_OPTS_FILE" \
    "$DB_DATABASE" \
    --single-transaction \
    --routines \
    --triggers \
    --hex-blob \
    --no-tablespaces \
    2>/tmp/backup_err.log \
  | gzip > "$FILE"

  EXIT_CODE=${PIPESTATUS[0]}

  if [ "$EXIT_CODE" -eq 0 ] && [ -s "$FILE" ]; then
    SIZE=$(du -sh "$FILE" | cut -f1)
    echo "[$(date)] ✓ Backup complete: ${FILE} (${SIZE})"
  else
    echo "[$(date)] ✗ Backup FAILED (exit code: ${EXIT_CODE})"
    cat /tmp/backup_err.log
    rm -f "$FILE"
  fi

  # Remove backups older than KEEP_DAYS
  DELETED=$(find "$BACKUP_DIR" -name "afinet_*.sql.gz" -mtime +"$KEEP_DAYS" -print -delete | wc -l)
  if [ "$DELETED" -gt 0 ]; then
    echo "[$(date)] Pruned ${DELETED} old backup(s) (>${KEEP_DAYS} days)"
  fi

  # List current backups
  echo "[$(date)] Current backups:"
  ls -lh "$BACKUP_DIR"/afinet_*.sql.gz 2>/dev/null || echo "  (none)"

  echo "[$(date)] Next backup in 6 hours."
  sleep "$INTERVAL"
done
