#!/bin/bash

# preset_mongodb_docker.sh - MongoDB preset data update script
# Usage: ./preset_mongodb_docker.sh [version] [local_file_path(optional)]

set -e

# Show usage information
show_usage() {
    echo "Usage: $0 [version] [local_file_path(optional)]"
    echo "Examples: "
    echo "  $0 6.5.0                                       # Download and use specified version"
    echo "  $0 6.5.0 /path/to/preset_mongodb_6.5.0.tar.gz  # Use local file"
    exit 1
}

# Check parameters
if [ $# -lt 1 ]; then
    echo "Error: At least one parameter (version) is required"
    show_usage
fi

VERSION="$1"
LOCAL_FILE="$2"
FILENAME="preset_mongodb_${VERSION}.tar.gz"

# Check if Docker is running
if ! docker info >/dev/null 2>&1; then
    echo "Error: Docker is not running or current user has no permission to access Docker"
    exit 1
fi

# Get container ID
CID=$(docker ps | grep -E 'community|hap:|hap-' | awk '{print $1}')
if [ -z "$CID" ]; then
    echo "Error: No container found"
    exit 1
fi

# Handle file source
if [ -n "$LOCAL_FILE" ]; then
    # Use local file
    if [ ! -f "$LOCAL_FILE" ]; then
        echo "Error: Local file does not exist: $LOCAL_FILE"
        exit 1
    fi
    echo "Using local file: $LOCAL_FILE"
else
    # Download file
    URL="https://pdpublic.mingdao.com/private-deployment/data/preset_mongodb_${VERSION}.tar.gz"
    echo "Downloading file: $URL"
    if ! wget "$URL"; then
        echo "Error: Failed to download file"
        exit 1
    fi
fi

# Check if file exists
if [ ! -f "./$FILENAME" ]; then
    echo "Error: File does not exist: ./$FILENAME"
    exit 1
fi

echo "Starting MongoDB preset data update version: $VERSION"

# Copy file to container
echo "Copying file to container..."
docker cp "./$FILENAME" "$CID:/tmp/"

# Extract file inside container
echo "Extracting file inside container..."
docker exec "$CID" tar -zxf "/tmp/$FILENAME" -C /init/mongodb/

# Execute region reset operation
echo "Executing region reset operation..."
docker exec "$CID" bash -c "source /entrypoint.sh && mongodbResetRegion"

# Execute translation template reset operation
echo "Executing translation template reset operation..."
docker exec "$CID" bash -c "source /entrypoint.sh && mongodbResetTemplateMessage"

# Clean up temporary files in container
echo "Cleaning up temporary files in container..."
docker exec "$CID" rm -f "/tmp/$FILENAME"

# Clean up local temporary files
echo "Cleaning up local temporary files..."
rm -f "./$FILENAME"

echo "MongoDB preset data update completed!"

