#!/usr/bin/env bash

# Default database path (adjust as needed)
# DEFAULT_DATABASE="/path/to/default/database"

# Parse command line arguments
while getopts "d:" opt; do
    case $opt in
        d) DATABASE="$OPTARG" ;;  # Specify database path with -d option
        *) echo "Usage: $0 [-d database_path]" ; exit 1 ;;
    esac
done

# Check if the database path exists
if [ ! -d "$DATABASE" ]; then
    echo "[❌] Error: Database directory does not exist: $DATABASE"
    exit 1
fi

echo "[🔄] Running ViOTUcluster_Test..."

# Execute ViOTUcluster_AllinOne command and output directly to terminal
ViOTUcluster_AllinOne -r "$CONDA_PREFIX/ViTest" -o "$CONDA_PREFIX/ViTest/Res" -d "$DATABASE" -a megahit --con 2>&1

# Check for success message in output (run again for checking message)
if ViOTUcluster_AllinOne -r "$CONDA_PREFIX/ViTest" -o "$CONDA_PREFIX/ViTest/Res" -d "$DATABASE" -a megahit --con 2>&1 | grep -q "All basic analysis completed successfully."; then
    echo "[✅] All module completed successfully. Pausing script execution."
    exit 1
fi

# Check if the command executed successfully
if [ $? -eq 0 ]; then
    echo "[✅] ViOTUcluster completed successfully."
    rm -rf "$CONDA_PREFIX/ViTest/Res"
else
    echo "Error: ViOTUcluster execution failed."
    read -p "Press y to open the result folder for inspection: " choice
    if [ "$choice" == "y" ]; then
        if command -v xdg-open &> /dev/null; then
            xdg-open "$CONDA_PREFIX/ViTest/Res"
        else
            echo "Cannot open the folder, please open it manually: $CONDA_PREFIX/ViTest/Res"
        fi
    fi
    echo "[✅] The result folder has been retained for inspection: $CONDA_PREFIX/ViTest/Res"
    exit 1
fi
