#!/bin/bash
# Usage: $0 <firefox|firefox-esr>
# Copyright (c) 2019 Danh Doan
# All rights reserved.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.

pkg=${1:-firefox}
tmpldir="$pkg-i18n"

case "${pkg}" in
firefox-esr) esr=esr ;;
firefox) : ;;
*)
	echo "Usage: $0 <firefox|firefox-esr>" >&2
	exit 1
	;;
esac

tmpoldfile="$(mktemp)"
tmpnewfile="$(mktemp)"

xoldlangexpr="^_languages="

cd "$(xdistdir)/srcpkgs"
source "${tmpldir}/template"

xlistold() {
	for _lang in "${_languages[@]}"; do
		_locale="${_lang%%\"*}"
		[ $_locale ] && echo "$_locale"
	done
}

xlink () {
	test -L "$tmpldir-$1" ||
	ln -sf "$tmpldir" "$tmpldir-$1"
}

xnewlang () {
	lang=$1
	padded=$(printf '%-7s' $lang)
	xoldexpr=$xoldlangexpr
	xoldlangexpr="'$lang \+\""
	grep -q "'$lang \+\"" "$tmpldir/template" && return 0
	sed -i "/$xoldexpr/a\\
	'$padded\"Unknown\"'
	/checksum=/a\\
 badbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadb" \
	"$tmpldir/template"
}

xprocessnew() {
	while read -r lang; do
		printf '%-7s\n' $lang >&3
		xlink $lang
		xnewlang $lang
	done
}

xcleanlang() {
	while read -r lang; do
		padded=$(printf '%-7s' $lang)
		sed -i "/'$padded\"/d" $tmpldir/template
		unlink "$tmpldir-$lang" || true
	done
}

xlistold >| "$tmpoldfile"

curl "https://ftp.mozilla.org/pub/firefox/releases/$version$esr/linux-i686/xpi/" \
	| grep -o 'xpi/[a-z]\+\(-[A-Z]\+\)\?' \
	| cut -d/ -f2 \
	| xprocessnew 3>$tmpnewfile

grep -vF -f $tmpnewfile $tmpoldfile \
	| xcleanlang

rm -rf $tmpoldfile $tmpnewfile
