#!/bin/bash

. ${TOOLKIT}-functions.sh

preferred=$(jtconf app-office.preferred_release)


files=$(list_install_files "pkgs-install-rel-$preferred")
echo -e "\n  INSTALL preferred release $preferred using install files: $files"
install_pkgs $(parse_installfiles $files)

# languages
#
pkgs=
for lang in $(jtconf app-office.languages)
do
	echo "  installing language: $preferred $lang"
	pkgs="$pkgs $(./listlocales $preferred $lang)"
done
install_pkgs $pkgs


# remove requested releases
#
for rel in $(jtconf app-office.remove_releases 2>/dev/null || :)
do
	files=$(list_install_files "pkgs-install-rel-$rel")
	echo -e "\n  REMOVE requested release $rel using install files: $files"
	remove_pkgs $(parse_installfiles $files)
done


# update commands in /usr/bin
#
program="/opt/libreoffice${preferred}/program/soffice"

echo -e "\n  updating alternatives for preferred release:"
[ -f /etc/alternatives/office ] && update-alternatives --remove-all office
[ -f /etc/alternatives/libreoffice ] && update-alternatives --remove-all libreoffice
update-alternatives --install /usr/bin/office office $program 20
update-alternatives --install /usr/bin/libreoffice libreoffice $program 20

# add/update installed release alternative commands
#
echo -e "\n  updating alternatives for all installed releases:"
for cmd_rel in $(cd /opt ; ls -d libreoffice[0-9]* 2>/dev/null || :)
do
	# clean up emtpy dir in case of release deinstall
	rmdir /opt/$cmd_rel 2>/dev/null || :

	program="/opt/$cmd_rel/program/soffice"
	[ -f "$program" ] && {
		[ -f /etc/alternatives/$cmd_rel ] && update-alternatives --remove-all $cmd_rel
		update-alternatives --install /usr/bin/$cmd_rel $cmd_rel $program 20
	}
done



# remove uninstalled ones
#
for cmd_rel in $(cd /usr/bin ; ls -d libreoffice[0-9]* 2>/dev/null || :)
do
	program="/opt/$cmd_rel/program/soffice"
	[ -f $program ] || {
		echo -e "\n  removing alternatives for no-more installed release $cmd_rel:"
		update-alternatives --remove-all $cmd_rel
	}
done

# clean old files
purgefiles /usr/local/bin/soffice

exit 0
