#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

# Define variables
PLUGIN_DIR="./plugins"
REPO_URL="https://maven.lavalink.dev/snapshots/dev/lavalink/youtube/youtube-plugin"
METADATA_URL="${REPO_URL}/maven-metadata.xml"
ARTIFACT_ID="youtube-plugin"

echo "Fetching latest snapshot version..."

# Fetch metadata and extract the latest snapshot version using grep and sed
# Use curl with -sS for silent operation but show errors
# Use grep to find the <latest> tag, then sed to extract the content
LATEST_VERSION=$(curl -sS "$METADATA_URL" | grep '<latest>' | sed -e 's/.*<latest>\(.*\)<\/latest>.*/\1/')

if [ -z "$LATEST_VERSION" ]; then
  echo "Error: Could not determine the latest snapshot version."
  exit 1
fi

echo "Latest snapshot version: $LATEST_VERSION"

# Construct the JAR filename and download URL
JAR_FILENAME="${ARTIFACT_ID}-${LATEST_VERSION}.jar"
DOWNLOAD_URL="${REPO_URL}/${LATEST_VERSION}/${JAR_FILENAME}"

# Create the plugins directory if it doesn't exist
mkdir -p "$PLUGIN_DIR"

# Remove any existing youtube-plugin JARs to avoid conflicts
echo "Removing old plugin versions from $PLUGIN_DIR..."
rm -f "$PLUGIN_DIR"/youtube-plugin-*.jar

# Download the latest snapshot JAR
echo "Downloading $JAR_FILENAME from $DOWNLOAD_URL..."
curl -L -o "$PLUGIN_DIR/$JAR_FILENAME" "$DOWNLOAD_URL"

# Verify download
if [ ! -f "$PLUGIN_DIR/$JAR_FILENAME" ]; then
    echo "Error: Failed to download the plugin JAR."
    exit 1
fi

echo "Successfully downloaded $JAR_FILENAME to $PLUGIN_DIR"
echo "Make sure to restart your Lavalink container for the changes to take effect."

exit 0
