#!/bin/bash

# Check if a volume name was provided
if [ $# -eq 0 ]; then
    echo "Error: No volume name provided."
    echo "Usage: $0 <volume_name>"
    exit 1
fi

# Get the volume name from the first argument
VOLUME_NAME=$1

# Define the local directory to copy logs to
LOCAL_DIR="./stackhero/logs"

# Create the local directory if it doesn't exist
mkdir -p "$LOCAL_DIR"

echo "Copying logs from Docker volume '$VOLUME_NAME' to $LOCAL_DIR"

# Create a temporary container with the volume mounted
CONTAINER_ID=$(docker run -d -v $VOLUME_NAME:/logs --name temp_log_container alpine sh -c 'tail -f /dev/null')

# Check if the container was created successfully
if [ $? -ne 0 ]; then
    echo "Error: Failed to create temporary container."
    exit 1
fi

# Copy files from the container to the local machine
docker cp $CONTAINER_ID:/logs/. "$LOCAL_DIR"

# Check if the copy was successful
if [ $? -eq 0 ]; then
    echo "Logs successfully copied to $LOCAL_DIR"
else
    echo "Error: Failed to copy logs from the container."
fi

# Remove the temporary container
docker rm -f $CONTAINER_ID

echo "Temporary container removed."