#!/usr/bin/env bash
set -euo pipefail

# ==============================================================================
# MongoDB Online Dump Script (Standalone Docker)
# ==============================================================================
#
# PURPOSE:
#   Creates an online backup of only the 'utility-bills' database using mongodump.
#   The database server remains running during the backup process.
#
# WHEN TO USE:
#   - For standalone Docker deployments (not Docker Swarm)
#   - When you need a quick backup without downtime
#   - When you only need the database content, not the full volume
#
# BACKUP TYPE:
#   - Online (hot) backup - DB server keeps running
#   - Database-level backup - only 'utility-bills' database
#   - Creates compressed archive (.tar.gz) using mongodump
#
# OUTPUT:
#   - Backup files stored in: ./mongo-backup/
#   - Filename format: utility-bills-dump-YYYY-MM-DD_HH-MM.tar.gz
#   - Log file: ./mongo-backup/db-dump-db-standalone.log
#   - Automatic rotation: keeps newest 7 backups (configurable via KEEP env var)
#
# USAGE:
#   ./db-dump--standalone.sh
#   KEEP=10 ./db-dump--standalone.sh  # Keep 10 backups instead of 7
#
# ==============================================================================

# Configuration

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# create backup directory if it doesn't exist
BACKUP_DIR="$SCRIPT_DIR/mongo-backup"
mkdir -p "$BACKUP_DIR"

# initialize log file (overwrite if exists)
LOG_FILE="$BACKUP_DIR/db-dump-db-standalone.log"
> "$LOG_FILE"

# Function to log messages
log() {
  local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
  echo "[$timestamp] $*" | tee -a "$LOG_FILE"
}

log "Starting database dump process..."

BACKUP_FILE_NAME_BASE="utility-bills-dump-"
BACKUP_FILE_NAME="${BACKUP_FILE_NAME_BASE}$(date +%F_%H-%M).tar.gz"

CONTAINER_NAME="evidencija-rezija__mongo"
DB_NAME="utility-bills"

docker exec "$CONTAINER_NAME" sh -c '
  mongodump \
    --username root \
    --password HjktJCPWMBtM1ACrDaw7 \
    --authenticationDatabase admin \
    --dumpDbUsersAndRoles \
    --db '$DB_NAME' \
    --archive=/backup/'$BACKUP_FILE_NAME' \
    --gzip
'

log "... DB dump created successfully."

# rotate old backups: keep only the newest $KEEP files
KEEP="${KEEP:-7}"
if [ "$KEEP" -gt 0 ]; then
  log "Rotating backups, keeping the newest $KEEP files."

  # gather files sorted newest-first
  mapfile -t files < <(ls -1t "$BACKUP_DIR"/${BACKUP_FILE_NAME_BASE}*.tar.gz 2>/dev/null || true)
  if [ "${#files[@]}" -gt "$KEEP" ]; then
    for f in "${files[@]:$KEEP}"; do
      log "Removing old backup: $f"
      rm -f -- "$f"
    done
  fi

  log "Rotation completed."
else
  log "Backup rotation disabled (KEEP=$KEEP)."
fi

log "Database backup process completed successfully."
