#!/bin/bash

ECPATH=$(type -p voxren)

ECPATH=${ECPATH%/voxren}
ECPATH=${ECPATH%/bin}
CONFPATH=${ECPATH}/share/eccet/config/modules/save/GENPPM
if [ "$1" == "-m" ]; then
	CONFPATH=${ECPATH}/share/eccet/config/modules/save/GENYUV
	shift
fi

echo "Install Path is $ECPATH"
echo

cd "$CONFPATH"

SUBSYSTEMS=$(ls *_*.test | sed -e "s/_.*\$//" | uniq)

if [ $# == 0 ] ; then
	echo "Current configuration: (-? for help)"
	for a in $SUBSYSTEMS; do
		TARGET=""
		if [ -L "$a" ] ; then
			TARGET=$(ls -l "$a" | sed -e "s/^.*-> *//")
			printf "%-20s => %s\n" $a $TARGET
		else
			printf "%-20s => %s\n" $a "not configured"
		fi
		ALTERNATIVES=$(ls ${a}_*.test | sed -e "s/\.test\$//" | tr "
" " ")
		for b in $ALTERNATIVES; do
			if [ "$b" == "$TARGET" ] ; then continue; fi
			printf "%-20s    %s\n" "" $b
		done
	done
	exit
fi

DO_DELETE=0
SUBSYS=""
DEFAULT=""

if [ "$1" == "-?" ] ; then
	echo "Usage: $0 [-m] subsystem default_setting"
	echo "Sets up or deletes which save module setup is to be used by "
	echo "the Eccet GUIs."
	echo "subsystem may be \"all\", if default_setting is \"none\","
	echo "which will delete alldefault settings."
	echo "The optional -m parameter will select the movie options"
	echo "instead of the default picture options."
	echo "See man ${0##*/} for details."
	exit 1
fi

SUBSYS="$1"
DEFAULT="$2"

if [ "$SUBSYS" == "all" -a "$DEFAULT" == "none" ] ; then
	echo "Do you want to delete all default settings? (yes or no)"
	while read a; do
		if [ "$a" == "yes" ]; then
			break;
		elif [ "$a" == "no" ] ;  then
			echo "O.k. - aborting."
			exit 1;
		else
			echo "Please answer yes or no."
		fi
	done
	echo "O.k. - deleting."
	for a in $SUBSYSTEMS; do
		rm -f "$a" "$a.test"
	done
fi

echo "You requested to set the default for $SUBSYS to $DEFAULT."

if [ "$DEFAULT" == "none" ] ; then
	if [ ! -L "$SUBSYS" ] ; then
		echo "No link found for $SUBSYS".
		exit 1;
	fi
	echo "Deleting default for $SUBSYS"
	rm -f "$SUBSYS" "$SUBSYS.test"
	exit 1
fi

if [ ! -f "$DEFAULT" ] ; then
	echo "Unknown Alternative \"$DEFAULT\"."
	exit 1
else
	PRETEST=${DEFAULT#${SUBSYS}_}
	if [ "$PRETEST" == "$DEFAULT" ] ; then
		echo "The option you selected exists, but is not intended for the given subsystem."
		echo "If you really want to do this, set the link manually."
		exit 1
	fi
	rm -f "$SUBSYS" "$SUBSYS.test"
	ln -s "$DEFAULT" "$SUBSYS"
	ln -s "$DEFAULT.test" "$SUBSYS.test"
	echo Done.
fi
