#!/usr/bin/env bash

# APT but only for fonts
# alex@aiei.ch
#
# selfupdate=https://raw.githubusercontent.com/alexmyczko/fnt/main/fnt

#TMPDIR="${TMPDIR:-/tmp}"
TMPDIR="${HOME}/.fnt"
# debian sid index
INDEX="http://ftp.ch.debian.org/debian/dists/sid/main/binary-all/Packages.xz"
# google fonts index
GINDEX="https://sid.ethz.ch/debian/google-fonts/fonts-master/"
MIRROR="http://ftp.ch.debian.org/debian/"

if ! which uname &>/dev/null; then
	s="Windows"
else
	s=$(uname -s)
fi

case "$s" in
	Darwin)
		#echo macOS
		check="curl brew otfinfo chafa"
		# otfinfo comes with lcdf-typetools
		i="brew"
		md5="md5"
		target="$HOME/Library/Fonts/"
	;;
	Linux|GNU/kFreeBSD|GNU)
		#echo Linux
		check="curl chafa otfinfo"
		i="apt"
		md5="md5sum"
		target="$HOME/.fonts/"
		if [ 0 -eq `id -u` ]; then
        		target="/usr/local/share/fonts/"
			mkdir -p $target
    		fi
	;;
	FreeBSD)
		#echo FreeBSD
		check="curl chafa otfinfo"
		i="pkg"
		md5="md5"
		target="$HOME/.fonts/"
	;;
	Haiku)
		#echo Haiku OS
		check="curl"
		i="pkgman"
		target="$HOME/config/non-packaged/data/fonts/"
	;;
	Windows)
		#echo Windows
		check="cmd.exe"
		alias which="where"
		i="ENOPKGMANAGER"
		target="$USERPROFILE\\Fonts"
	;;
	*)
		echo "Please report $s to https://github.com/alexmyczko/fnt/issues"
		exit 1
	;;
esac

for a in $check; do
    if ! which "$a" &>/dev/null; then
        echo "$a not found, please use $i to install it."
        exit 1
    fi
done

if [ "${1}x" = 'x' ]; then
	echo "Syntax: fnt [ update | list | info ]"
	echo "        fnt [ install | remove | preview | search ] font"
	echo
	echo "update|-u  updates the font package index of debian sid"
	echo "list|-l    lists installed fonts with glyphcount per font"
	echo "info       information about how many fonts can be installed"
	echo "install|-i install a font"
	echo "remove|-r  remove a font"
	echo "preview|-p preview a font"
	echo "search|-s  search for font"
	echo
	exit 0
fi

case "$1" in
	update|-u)
		echo Updating...
		if [ ! -d "${TMPDIR}" ]; then mkdir -p "${TMPDIR}"; fi
	        if [ -f "${TMPDIR}/Packages.xz" ]; then rm "${TMPDIR}/Packages.xz"; fi
        	curl -s "$INDEX" -o "${TMPDIR}/Packages.xz"
	;;

	info)
		echo "Information..."
		echo "Available Fonts: $(fnt search | wc -l)"
	;;

	list|-l)
		# echo Listing...
		# macOS mainly comes with *.ttc (truetype font collections, that can not be processed by otfinfo)
		#ls -1 /System/Library/Fonts/*.?tf /usr/share/fonts/*type/*/*.?tf $HOME/Library/Fonts/*.?tf $HOME/.fonts/*.?tf 2>/dev/null | while read f; do
		ls -1 $HOME/Library/Fonts/*.?tf $HOME/.fonts/*.?tf /usr/local/share/fonts/*.?tf 2>/dev/null | while read f; do
			echo "$f" [$(otfinfo -u "$f" 2>/dev/null|wc -l|awk '{print $1}')] | sed s,.*/,,
		done
	;;
	preview|-p)
		# echo Previewing...
		curl -L -s "https://screenshots.debian.net/screenshot/fonts-$2" -o "${TMPDIR}/preview.png"
		md5s=$($md5 ${TMPDIR}/preview.png)
                echo $md5s |grep b5765b390157e36eaf721c8848a4b04d >/dev/null &&
                  curl -L -s "https://bootes.ethz.ch/fonts/$2/preview.png" -o "${TMPDIR}/preview.png"
		#chafa --invert -c none --symbols block+border-solid "${TMPDIR}/preview.png"
		chafa -c 240 -w 9 -O 9 -p on --symbols all "${TMPDIR}/preview.png"
	;;
	install|-i)
		if [ ! -f "${TMPDIR}/Packages.xz" ]; then
			echo "Could not find ${TMPDIR}/Packages.xz"
			echo "Please run $0 update"
			# could also just run itself with update...
			exit 1
		fi
		if [ ! -d "${target}" ]; then
			mkdir -p "${target}"
		fi
		# cat $HOME/.fnt/Packages.xz |unxz|grep "^Package:\|^Homepage:\|^Size:\|^Installed-Size:\|^Description:"
		# cat $HOME/.fnt/Packages.xz |unxz| awk '!NF{print line; line=""}{line=line " " $0}' |grep "Package: fonts-"
		p=$(unxz -c "$HOME/.fnt/Packages.xz" | grep -v "^Architecture:\|^Section:\|^Priority:\|^Replaces:\|^Provides:\|^Brekas:\|^Maintainer:\|^MD5sum:\|^Source:\|^Breaks:\|^Multi-Arch:\|^Description-\|^Tag:\|^SHA256:"|awk '!NF{print line; line=""}{line=line " " $0}' |grep "Package: fonts-"|grep "fonts-$2"|head -1)
		# Package: fonts-agave Version: 37-1 Installed-Size: 364 Description: monospaces programming font Homepage: https://b.agaric.net/page/agave Filename: pool/main/f/fonts-agave/fonts-agave_37-1_all.deb Size: 103112

        	if [ -z "$p" ]; then
		    q=$(curl -s "$GINDEX/ofl/" |grep "a href" |sed 's,.*">,google-,;s,/.*,,' |grep "$2" | head -1)
		    s=$(curl -s "$GINDEX/apache/" |grep "a href" |sed 's,.*">,google-,;s,/.*,,' |grep "$2" | head -1)

		    if [ -z "$q" ] && [ -z "$s" ]; then
        		echo "Font \"$2\" not found"
        		exit 1
		    else
			echo "Installing google-${2}"
			# here comes the google web font installer part using grep '\..tf'
			curl -s "$GINDEX/ofl/${2}/" |grep "a href" |grep "\..tf" |sed 's,.*tf.>,,' | sed 's,</..*,,' | while read f; do
			    curl -g -s "${GINDEX}/ofl/${2}/$f" -o "$target/$f"
			done
			curl -s "$GINDEX/apache/${2}/" |grep "a href" |grep "\..tf" |sed 's,.*tf.>,,' | sed 's,</..*,,' | while read f; do
			    curl -g -s "${GINDEX}/apache/${2}/$f" -o "$target/$f"
			done
			exit 0
		    fi
	        fi

		name=$(echo "$p" | awk '{print $2}')
		ver=$(echo "$p" | awk '{print $4}')
		instsize=$(echo "$p" | awk '{print $6}')
		downsize=$(echo "$p" | awk '{print $NF}')
		url=$(echo "$p" | awk '{print $(NF-2)}')
		f=$(basename "$url")
		echo "Installing ${name} ${ver} [${downsize} ${instsize}000 ${MIRROR}${url}]..."
		curl -s "${MIRROR}${url}" -o "${TMPDIR}/$f"
		cd "${TMPDIR}" || exit 1
		ar x "$f"
		tar xJf data.tar.xz
		find "${TMPDIR}" . -name "*.?tf" -exec cp {} "$target" \;
		rm "$f" control.tar* data.tar* debian-binary
		rm -rf "${TMPDIR:?}/usr"
	;;
	remove|-r)
		echo "Removing..."
		echo "Feel free to send patches or dollars (see the sponsor link)"
	;;
	search|-s)
		unxz -c "$HOME/.fnt/Packages.xz" |grep ^Package:\ fonts-|awk '{print $2}' | grep "$2"
		curl -s "$GINDEX/ofl/" |grep "a href" |sed 's,.*">,google-,;s,/.*,,' |grep -v "\.\.$" |grep "$2"
		curl -s "$GINDEX/apache/" |grep "a href" |sed 's,.*">,google-,;s,/.*,,' |grep -v "\.\.$" |grep "$2"
	;;
	moo)
		echo "This fnt does not have cow powers."
	;;
	wak)
		echo ' _()< wak wak'
		echo '(__)'
	;;
	*)
		echo "Nothing..."
	;;
esac
