#!/bin/bash

#Get the original user name:
ORIGUSER=`logname`

#Function that will install the script (first time):
function inst {
	#make directory
	mkdir -p $HOME/.config/libreoffice/4/user/basic/mpmastools
	#copy menubar
	cp -v basic/* $HOME/.config/libreoffice/4/user/basic/mpmastools
	cp -v menubar/menubar.xml $HOME/.config/libreoffice/4/user/config/soffice.cfg/modules/scalc/menubar
	#add lines to .xlc files
	echo "Adjusting Libre Office dialogs and scripts"
	head -n -1 $HOME/.config/libreoffice/4/user/basic/dialog.xlc > header.txt
	cat header.txt xlc/dialog.xlc > $HOME/.config/libreoffice/4/user/basic/dialog.xlc
	head -n -1 $HOME/.config/libreoffice/4/user/basic/script.xlc > header.txt
	cat header.txt xlc/script.xlc > $HOME/.config/libreoffice/4/user/basic/script.xlc
	rm header.txt
	#change group ownership
	chown $ORIGUSER -R $HOME/.config/libreoffice/4/user
	echo "Installation completed" 
}

#Function that will reinstall the script:
function reinst {
	#make directory
	mkdir -p $HOME/.config/libreoffice/4/user/basic/mpmastools
	#copy menubar
	cp -v basic/* $HOME/.config/libreoffice/4/user/basic/mpmastools
	cp -v menubar/menubar.xml $HOME/.config/libreoffice/4/user/config/soffice.cfg/modules/scalc/menubar
	#change group ownership
	chown $ORIGUSER -R $HOME/.config/libreoffice/4/user
	echo "Re-installation completed" 
}


#Check if the library is already installed:
if grep -q 'library:name="mpmastools"' $HOME/.config/libreoffice/4/user/basic/dialog.xlc
#If yes than ask if it should be reinstalled (and do)
then
	echo "Library is already installed. Would you like to update it with this version? (Y/N)"
	while true; do 
		read yn
		case $yn in
			[Yy]* ) reinst; break;;
			[Nn]* ) exit;;
			* ) echo "Please answer Y or N";;
		esac
	done
else
#If not - install the library
	inst
fi
