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

# ==============================================================================
# MongoDB Dump Restore Script (Standalone Docker)
# ==============================================================================
#
# PURPOSE:
#   Restores the 'utility-bills' database from a mongodump archive.
#   The database server remains running during the restore process.
#
# WHEN TO USE:
#   - For standalone Docker deployments (not Docker Swarm)
#   - To restore from dumps created by db-dump--standalone.sh
#   - When you need to restore without shutting down the database
#
# RESTORE TYPE:
#   - Online (hot) restore - DB server keeps running
#   - Database-level restore - only 'utility-bills' database
#   - Drops existing collections before restoring (--drop flag)
#
# INPUT:
#   - Requires dump filename as parameter
#   - Looks for file in: ./mongo-backup/
#   - Log file: ./mongo-backup/db-restore-from-dump.log
#
# USAGE:
#   ./db-restore-from-dump--standalone.sh <dump-filename>
#   ./db-restore-from-dump--standalone.sh utility-bills-dump-2025-11-26_14-30.tar.gz
#
# WARNING:
#   This will DROP all existing collections in the 'utility-bills' database
#   before restoring. Make sure you have a backup if needed!
#
# ==============================================================================

# 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-restore-from-dump.log"
> "$LOG_FILE"

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

# Check if dump filename is provided
if [ $# -eq 0 ]; then
  log "Error: No dump filename provided"
  log "Usage: $0 <dump-filename>"
  log "Example: $0 utility-bills-dump-2025-11-26_14-30.tar.gz"
  exit 1
fi

DUMP_FILENAME="$1"
DUMP_FILE="$BACKUP_DIR/$DUMP_FILENAME"

# Check if dump file exists
if [ ! -f "$DUMP_FILE" ]; then
  log "Error: Dump file not found: $DUMP_FILE"
  exit 1
fi

log "Starting database restore process..."
log "Restoring from: $DUMP_FILE"

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

docker exec "$CONTAINER_NAME" sh -c '
  mongorestore \
    --username root \
    --password HjktJCPWMBtM1ACrDaw7 \
    --authenticationDatabase admin \
    --db '$DB_NAME' \
    --archive=/backup/'$DUMP_FILENAME' \
    --gzip \
    --drop
'

log "Database restore completed successfully."
