#!/bin/sh

_ofhome=/var/lib/openfire
_plugdir=/usr/share/openfire/plugins

for conf in "$_ofhome"/conf/openfire.xml \
	"$_ofhome"/conf/security.xml \
	"$_ofhome"/resources/security/client.truststore \
	"$_ofhome"/resources/security/keystore \
	"$_ofhome"/resources/security/truststore
do
	if [ -f "$conf" ]
	then
		printf "$conf exists. Not creating new one. \n\n"
	else
		printf "Copying new $conf \n"
		install -Dm600 -o openfire -g openfire "$conf".default "$conf" \
			|| printf "Copying new $conf failed.\n\n"
	fi
done

# Packaged plugins live under /usr; /var/lib/openfire/plugins is a symlink.
# apk cannot replace an existing directory with that symlink on upgrade.
mkdir -p "$_plugdir"
if [ -d "$_ofhome/plugins" ] && [ ! -L "$_ofhome/plugins" ]; then
	printf "Migrating %s/plugins to %s\n" "$_ofhome" "$_plugdir"
	for _p in "$_ofhome/plugins"/*; do
		[ -e "$_p" ] || continue
		_base=$(basename "$_p")
		if [ ! -e "$_plugdir/$_base" ]; then
			cp -a "$_p" "$_plugdir/"
		fi
	done
	rm -rf "$_ofhome/plugins"
fi
if [ ! -L "$_ofhome/plugins" ]; then
	rm -rf "$_ofhome/plugins"
	ln -sf "$_plugdir" "$_ofhome/plugins"
fi
