#!/bin/bash
#
# kopano4ucs
#   update configuration files
#
# Copyright 2012-2019 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

diffOptions () {

	local file="$1"
	local orig="$(echo $file | sed 's/.dpkg-dist//')"
	local options="$(cat $file | egrep -v '^[[:blank:]]*#'| sort -u| awk '{print $1}')"
	local newOption=""
	local comment=""
	local backupFile="$orig.$(date +%Y%m%d-%H%M%S)"
	
	if [ ! -e "$orig" -o ! -e "$file" ]; then
		return
	fi
	
	for option in $options; do
		comment=""
		newOption=""
		if ! egrep -q "^[[:blank:]]*$option[[:blank:]]*=" "$orig"; then
			newOption="$(egrep "^[[:blank:]]*$option[[:blank:]]*=" "$file")"
			comment="$(egrep -B 20 "^[[:blank:]]*$newOption" "$file" | perl -e 'print reverse <>' | sed '/^$/,$d')"
			comment="$(echo "$comment" | perl -e 'print reverse <>' | egrep '^[[:blank:]]*#')"
			if [ -n "$newOption" ]; then
				if [ "$writeConfig" = "true" ]; then
					# save orig once
					if [ ! -f "$backupFile" ]; then
						cp "$orig" "$backupFile"
					fi
					echo "" >> $orig
					echo "$comment" >> $orig
					echo "$newOption" >> $orig
				else
					echo ""
					echo "$orig:"
					echo "$comment"
					echo "$newOption"
				fi
			fi
		fi
	done
}

usage () {

	echo "$(basename $0) OPTIONS"
	echo "  Updates the kopano configurations files with new"
	echo "  configuration options."
	echo ""
	echo "Options:"
	echo "  -w     append new configuration options to config files"
	echo "  -h     display this message"

	exit 1
}


writeConfig=false
while getopts ":hw" opt; do
	case $opt in
		w)
			writeConfig=true
			;;
		h)
			usage
			;;
		\?)
			echo "Invalid option: -$OPTARG" >&2
			usage
			;;
		:)
			echo "Option -$OPTARG requires an argument." >&2
			usage
			;;
	esac
done

# update new configuration options
files=$(ls /etc/kopano/*.dpkg-dist)
for file in $files; do
	diffOptions "$file"
done
