#!/bin/bash

# Variables
VERSION_URL="https://raw.githubusercontent.com/samtupy/nvgt/main/version"
DOWNLOAD_BASE_URL="https://nvgt.gg/downloads"
INSTALL_DIR="/opt/nvgt"  # Install location (adjust as needed)
BINARY_LINK="/usr/local/bin/nvgt"  # Symlink for global access

# Step 1: Fetch the latest version
echo "Checking the latest NVGT version..."
LATEST_VERSION=$(curl -s "$VERSION_URL" | head -n 1 | tr -d '[:space:]')
if [ -z "$LATEST_VERSION" ]; then
    echo "Error: Could not retrieve the latest version."
    exit 1
fi

# Convert version format to match the download URL (replace dash with underscore)
VERSION_WITH_UNDERSCORE=$(echo "$LATEST_VERSION" | sed 's/-/_/g')

# Step 2: Construct the download URL
DOWNLOAD_URL="$DOWNLOAD_BASE_URL/nvgt_${VERSION_WITH_UNDERSCORE}.tar.gz"

# Step 3: Download the latest version
echo "Downloading NVGT version $LATEST_VERSION..."
curl -L -o "/tmp/nvgt_${VERSION_WITH_UNDERSCORE}.tar.gz" "$DOWNLOAD_URL"
if [ $? -ne 0 ]; then
    echo "Error: Failed to download NVGT."
    exit 1
fi

# Step 4: Extract the downloaded file
echo "Extracting NVGT..."
sudo mkdir -p "$INSTALL_DIR"
sudo tar -xzf "/tmp/nvgt_${VERSION_WITH_UNDERSCORE}.tar.gz" -C "$INSTALL_DIR"
if [ $? -ne 0 ]; then
    echo "Error: Failed to extract NVGT."
    exit 1
fi

# Step 5: Set up system-wide access
echo "Setting up NVGT for global access..."
sudo ln -sf "$INSTALL_DIR/nvgt" "$BINARY_LINK"
if [ $? -ne 0 ]; then
    echo "Error: Failed to create symlink for NVGT."
    exit 1
fi

# Step 6: Set appropriate permissions
echo "Setting permissions..."
sudo chmod +x "$INSTALL_DIR/nvgt"
sudo chmod -R 755 "$INSTALL_DIR"
if [ $? -ne 0 ]; then
    echo "Error: Failed to set permissions."
    exit 1
fi

# Step 7: Verify setup
echo "Verifying NVGT installation..."
if command -v nvgt >/dev/null 2>&1; then
    echo "NVGT installed successfully. Run 'nvgt' to start it."
else
    echo "Error: NVGT installation failed."
    exit 1
fi
