#!/bin/sh

set -e

beginsWith()
{
	case $2 in
	$1*)
		true;;
	*)
		false;;
	esac;
}

bailOut()
{
	echo "No permissions to copy $SPECFILE to $KDB_DB_SPEC"
	echo "Are you root?"
	exit 1
}

if [ -z "$KDB" ]; then
	KDB=kdb
fi

if [ -z "$KDB_DB_SPEC" ]; then
	KDB_DB_SPEC=/usr/share/elektra/specification
fi


if [ $# -ne 2 ]; then
	echo "Usage: $0 specfile mountpoint"
	exit 1
fi

SPECFILE=$1
MOUNTPOINT=$2

if ! beginsWith / $MOUNTPOINT; then
	echo "Mountpoint needs to start with / (cascading mountpoint)"
fi

#current workaround: copy and not import to fully preserve syntax
cp $SPECFILE $KDB_DB_SPEC || bailOut

#now lets mount specification
$KDB mount $SPECFILE spec$MOUNTPOINT ni

FILENAME=`$KDB getmeta spec$MOUNTPOINT filename`
PLUGINS=""
i=0
while $KDB getmeta spec$MOUNTPOINT "needs/#$i"
do
	PLUGIN=`$KDB getmeta spec$MOUNTPOINT "needs/#$i"`
	PLUGINS="$PLUGINS $PLUGIN"
	i=$((i+1))
done

#now lets mount cascading mountpoint
$KDB mount $FILENAME $MOUNTPOINT $PLUGINS

