#!/usr/bin/make -f

# Definition of weights for each family font.
weights = Black ExtraBold Bold SemiBold Neutral Medium Light ExtraLight Thin
weights += Extrabold Semibold Extralight
weights := $(weights) $(patsubst %,%Italic,$(weights))
weights := $(weights) $(foreach distortion,ExtraCondensed Condensed SemiCondensed,$(patsubst %,$(distortion)%,$(weights)))
weights := $(patsubst Neutral,Regular,$(weights))

# Weights for -extra packages.
EXTRA_WEIGHTS := -XBlack -XExtraBold -XExtrabold -XSemiBold -XSemibold -XMedium -XLight -XExtraLight -XThin -XCondensed -XExtraCondensed

SUBSTVARS_PKGS := fonts-noto-core fonts-noto-extra fonts-noto-ui-core fonts-noto-ui-extra fonts-noto-unhinted

%:
	dh $@

override_dh_auto_build:
# Build WOFF2 fonts for fonts-noto-web package.
	chmod +x debian/scripts/generate-noto-web.sh
	./debian/scripts/generate-noto-web.sh
	dh_auto_build

override_dh_bugfiles:
# Force bug installation in all packages.
	dh_bugfiles --all

override_dh_install:
# Fill the hinted-udeb package.
	find . -path ./debian -prune -o \( \
	-name "NotoSansSinhala-Regular.ttf" -o \
	-name "NotoSansSinhala-Bold.ttf" -o \
	-name "NotoSerifGujarati-Regular.ttf" -o \
	-name "NotoSerifGujarati-Bold.ttf" \
	\) -print | xargs -I {} dh_install -pfonts-noto-hinted-udeb {} usr/share/fonts/truetype/noto/

# Fill the unhinted-udeb package.
	find . -path ./debian -prune -o -type f -name "*.ttf" -print | \
	grep -E "Noto(Kufi|Looped|Music|Naskh|Nastaliq|Rashi|Sans|Serif|Traditional|Math|Mono|Symbols|TamilSupplement)" | \
	grep -vE "(UI|VF|Condensed|Semi|Medium|Thin|Black|Light)" | \
	grep -vE "NotoSansTibetan-(Bold|Regular)\.ttf" | \
	grep -E "\-(Regular|Bold|Italic|BoldItalic|Slanted|Slanted-Bold)\.ttf$$" | \
	sort | \
	xargs -I {} dh_install -pfonts-noto-unhinted-udeb {} usr/share/fonts/truetype/noto/

# Fill the fonts-noto*.deb packages.
	dh_install -pfonts-noto-mono
	dh_install -pfonts-croscore
	dh_install -pfonts-noto-web
	dh_install -pfonts-noto-ui-core -XMono $(EXTRA_WEIGHTS)
	dh_install -pfonts-noto-core -XUI -XMono $(EXTRA_WEIGHTS)
	dh_install -pfonts-noto-extra -XUI
	dh_install -pfonts-noto-ui-extra
	dh_install --remaining-packages

override_dh_link:
	dh_link
	dh_link -pfonts-noto-web /usr/share/fonts/woff2/noto /usr/share/javascript/fonts-noto/woff2

override_dh_gencontrol:
# Dynamically generates the list of font families for the description of each package.
	for pkg in $$(dh_listpackages); do \
		if [ -d debian/$$pkg/usr/share/fonts/truetype/noto ]; then \
			LIST=$$(find debian/$$pkg/usr/share/fonts/truetype/noto -name "*.ttf" | \
				xargs -r otfinfo -a | cut -d: -f2 | sed 's/^[[:space:]]*//;s/[[:space:]]*$$//' | LC_ALL=C sort -u | \
				tr '\n' ',' | sed 's/,$$//; s/,/\$${Newline} * /g'); \
			echo "fonts:familylist= * $$LIST" > debian/$$pkg.substvars; \
		fi; \
	done
	dh_gencontrol -- -Vfonts:scriptcount="103"
