#!/bin/bash
# ~/.local/bin/font-manager
# This script extracts font archives and rebuilds font cache

FONT_DIR="$HOME/.local/share/fonts"
ARCHIVE_DIR="$FONT_DIR/archives"
ACTIVE_DIR="$FONT_DIR/active"

# Function to extract a specific font archive
extract_font() {
	local archive="$1"
	if [ -f "$ARCHIVE_DIR/$archive.tar.gz" ]; then
		echo "Extracting $archive fonts..."
		tar -xzf "$ARCHIVE_DIR/$archive.tar.gz" -C "$ACTIVE_DIR"
		fc-cache -f
		echo "Done! $archive fonts are now active."
	else
		echo "Error: Font archive $archive.tar.gz not found."
		exit 1
	fi
}

# Function to list available font archives
list_fonts() {
	echo "Available font archives:"
	ls -1 "$ARCHIVE_DIR" | sed 's/\.tar\.gz$//'
}

# Function to rebuild font cache
rebuild_cache() {
	echo "Rebuilding font cache..."
	fc-cache -f
	echo "Done!"
}

# Function to extract all fonts
extract_all() {
	echo "Extracting all font archives..."
	for archive in "$ARCHIVE_DIR"/*.tar.gz; do
		tar -xzf "$archive" -C "$ACTIVE_DIR"
	done
	fc-cache -f
	echo "Done! All fonts are now active."
}

# Function to clean active fonts directory
clean_fonts() {
	echo "Cleaning active fonts directory..."
	find "$ACTIVE_DIR" -type f -name "*.ttf" -o -name "*.otf" | xargs rm -f
	echo "Done! Active fonts directory is now clean."
}

# Main script logic
case "$1" in
"extract")
	extract_font "$2"
	;;
"list")
	list_fonts
	;;
"rebuild")
	rebuild_cache
	;;
"all")
	extract_all
	;;
"clean")
	clean_fonts
	;;
*)
	echo "Usage: font-manager [command] [options]"
	echo "Commands:"
	echo "  extract [name]   Extract specific font archive"
	echo "  list             List available font archives"
	echo "  rebuild          Rebuild font cache"
	echo "  all              Extract all font archives"
	echo "  clean            Remove all active fonts"
	;;
esac
