#!/bin/sh
# Copyright (c) 2000-2013 Synology Inc. All rights reserved.

source `dirname "$0"`/lib

PACKAGE_NAME="SVN"
VERSION="0001"
UPGRADE_CONF="/tmp/.${PACKAGE_NAME}.conf"
USER_CONF="/var/packages/$PACKAGE_NAME/user.conf"
TARGET="/var/packages/$PACKAGE_NAME/target"
REPO_LINK="$TARGET/repo"

linkBinary() {
	local x=
	local bin_name=
	for x in $TARGET/bin/*; do
		bin_name=`basename $x`
		target_path=/usr/bin/$bin_name
		
		if [ ! -e "$target_path" ]; then
			ln -s $x $target_path
		fi
	done
}

unlinkBinary() {
	local x=

	for x in $TARGET/bin/*; do
		local bin_name=`basename $x`

		if [ -L /usr/bin/$bin_name ]; then
			rm -f /usr/bin/$bin_name
		fi
	done
}

preinst() {
	exit 0
}

postinst() {
	if [ -f $UPGRADE_CONF ]; then
		cat $UPGRADE_CONF
		pkgwizard_dataroot="`/bin/get_key_value $UPGRADE_CONF share_name`"
	fi
	if [ -z "$pkgwizard_dataroot" ]; then
		pkgwizard_dataroot="svn"
	fi

	local data_path="/`get_package_volume $PACKAGE_NAME`/$pkgwizard_dataroot"

	linkBinary
	write_user_conf "$USER_CONF" "$PACKAGE_NAME" "$VERSION" "" "$pkgwizard_dataroot"
	if ! synoshare --get $pkgwizard_dataroot; then
		/usr/syno/sbin/synoshare --add "$pkgwizard_dataroot" "" "$data_path" "" "" "" 0 0
	fi
	ln -s $data_path $REPO_LINK

	exit 0
}

preuninst() {
	rm -f $REPO_LINK
	if [ "$pkgwizard_remove_dataroot" = "true" ]; then
		local share_name="`grep share_name $USER_CONF | cut -d= -f2 | cut -d'\"' -f2`"

		if ! synoshare --del TRUE "$share_name"; then
			echo "$share_remove_failed" >> $SYNOPKG_TEMP_LOGFILE
		fi
	fi
	rm "$USER_CONF"
	unlinkBinary

	exit 0
}

postuninst() {
	exit 0
}

preupgrade() {
	local share_name="`/bin/get_key_value $USER_CONF share_name`"

	echo "share_name=\"$share_name\"" > $UPGRADE_CONF

	exit 0
}

postupgrade() {
	rm $UPGRADE_CONF
	exit 0
}
