#!/bin/bash

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

FONT_NAME="UbuntuSans"
FONT_ZIP="${FONT_NAME}.zip"
# Simplified directory: removed the "NerdFonts" subfolder
FONT_DIR="$HOME/.local/share/fonts/${FONT_NAME}"
TMP_DIR=$(mktemp -d)

echo "Searching for the latest release of $FONT_NAME Nerd Font..."

# Use GitHub API to find the latest release download URL for UbuntuSans.zip
DOWNLOAD_URL=$(curl -s https://api.github.com/repos/ryanoasis/nerd-fonts/releases/latest \
    | grep "browser_download_url.*${FONT_ZIP}" \
    | cut -d '"' -f 4)

if [ -z "$DOWNLOAD_URL" ]; then
    echo "Error: Could not find the download URL for $FONT_NAME. Check your internet connection or GitHub API limits."
    rm -rf "$TMP_DIR"
    exit 1
fi

echo "Latest version found!"
echo "Downloading from: $DOWNLOAD_URL"

# Download the zip file to the temporary directory
curl -L -q "$DOWNLOAD_URL" -o "$TMP_DIR/$FONT_ZIP"

echo "Extracting fonts..."
# Ensure unzip is installed (will fail gracefully if not)
if ! command -v unzip &> /dev/null; then
    echo "Error: 'unzip' is not installed. Please install it using 'sudo apt install unzip' and try again."
    rm -rf "$TMP_DIR"
    exit 1
fi

unzip -q -o "$TMP_DIR/$FONT_ZIP" -d "$TMP_DIR/extracted"

echo "Installing fonts to $FONT_DIR..."
# Create the simplified font directory if it doesn't exist
mkdir -p "$FONT_DIR"

# Move only the TrueType (.ttf) or OpenType (.otf) files to the fonts directory
find "$TMP_DIR/extracted" -name '*.[ot]tf' -type f -exec cp {} "$FONT_DIR/" \;

echo "Updating the system font cache..."
fc-cache -f "$FONT_DIR"

echo "Cleaning up temporary files..."
rm -rf "$TMP_DIR"

echo "Done! $FONT_NAME Nerd Font has been successfully installed."