#!/bin/bash

GREEN='\033[0;32m'
RESET='\033[0m'

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

ZIP_PATH=$(ls "$SCRIPT_DIR/../../"*.zip 2>/dev/null | head -n 1)

if [ -n "$ZIP_PATH" ]; then
    SOURCE_FOR_VERSION=$(basename "$ZIP_PATH")
else
    SOURCE_FOR_VERSION=$(basename "$(realpath "$SCRIPT_DIR/..")")
fi

VERSION_NUM=$(echo "$SOURCE_FOR_VERSION" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "unknown")

PLUGIN_NAME="NAM Studio"
SRC_VST3="$SCRIPT_DIR/Data/Plugins/$PLUGIN_NAME.vst3"
SRC_LV2="$SCRIPT_DIR/Data/Plugins/$PLUGIN_NAME.lv2"
SRC_LIB="$SCRIPT_DIR/Data/Library/Factory Library.zip"

VST3_DEST="$HOME/.vst3"
LV2_DEST="$HOME/.lv2"
LIB_DEST="$HOME/Documents/VZtec/$PLUGIN_NAME"

animated_dots() {
    for ((i = 0; i < 50; i++)); do echo -n "."; sleep 0.01; done
    echo ""
}

install_vst3() {
    if [ -d "$SRC_VST3" ]; then
        mkdir -p "$VST3_DEST"
        cp -r "$SRC_VST3" "$VST3_DEST/"
        chmod -R 755 "$VST3_DEST/$PLUGIN_NAME.vst3"
        printf "${GREEN}VST3 installed: $VST3_DEST/$PLUGIN_NAME.vst3${RESET}\n"
    else
        echo "Error: Source VST3 not found at $SRC_VST3"
    fi
}

install_lv2() {
    if [ -d "$SRC_LV2" ]; then
        mkdir -p "$LV2_DEST"
        cp -r "$SRC_LV2" "$LV2_DEST/"
        chmod -R 755 "$LV2_DEST/$PLUGIN_NAME.lv2"
        printf "${GREEN}LV2 installed: $LV2_DEST/$PLUGIN_NAME.lv2${RESET}\n"
    else
        echo "Error: Source LV2 not found at $SRC_LV2"
    fi
}


install_library() {
    if ! command -v unzip &> /dev/null; then
        echo "Error: 'unzip' is not installed. Please install it with: sudo apt install unzip"
        exit 1
    fi

    if [ -f "$SRC_LIB" ]; then
        echo "Installing Factory Library (System)..."
        mkdir -p "$LIB_DEST"
        
        # Copiamos el archivo
        cp "$SRC_LIB" "$LIB_DEST/"
        
        # Descomprimimos y, SI TIENE ÉXITO (&&), borramos el zip original en el destino
        echo "Extracting files..."
        unzip -q -o "$LIB_DEST/Factory Library.zip" -d "$LIB_DEST/" && rm "$LIB_DEST/Factory Library.zip"
        
        chmod -R 755 "/opt/VZtec"
        animated_dots
        printf "${GREEN}Library installed successfully and cleanup done at: $LIB_DEST${RESET}\n"
    else
        echo "Error: Factory Library.zip not found at $SRC_LIB"
    fi
}

echo ""
echo "Installing $PLUGIN_NAME (version $VERSION_NUM)"
echo "---------------------------------------"
read -p "Install VST3? (y/n): " q_vst3
read -p "Install LV2? (y/n): " q_lv2
echo "Installing Factory Library (Required)..."
echo ""
animated_dots

if [[ $q_vst3 =~ ^[Yy]*$ ]]; then install_vst3; fi
if [[ $q_lv2 =~ ^[Yy]*$ ]]; then install_lv2; fi

install_library;

echo ""
printf "${GREEN}$PLUGIN_NAME $VERSION_NUM installation complete!${RESET}\n"