#!/bin/sh
#
# script to load/save all the vars in speakup
#
#  Copyright (C) 2009 the speakup team
#  Copyright (C) 2008 Steve Holmes
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
#  (at your option) any later version.
#
#   This program is distributed 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

die()
{
	echo $*
	exit 1
}

load()
{
	if [ ! -d $SAVEDIR ] ; then
		die no directory $SAVEDIR
	fi
	cd $SAVEDIR
	if [ -d i18n -a -d $SPEAKUPDIR/i18n ]; then
		cd i18n
		for f in *; do
			if [ -w $SPEAKUPDIR/i18n/$f ]; then
				cp $f $SPEAKUPDIR/i18n
			fi
		done
		cd ..
	fi
	for f in *; do
		if [ -w $SPEAKUPDIR/$f  -a -f $SPEAKUPDIR/$f ]; then
			cp $f $SPEAKUPDIR
		fi
	done
	if [ -d $SYNTH -a -d $SPEAKUPDIR/$SYNTH ]; then
		cd $SYNTH
		for f in *; do
			if [ -w $SPEAKUPDIR/$SYNTH/$f ]; then
				cp $f $SPEAKUPDIR/$SYNTH
			fi
		done
		cd ..
	fi
}

save()
{
	if [ ! -d $SAVEDIR ] ; then
		echo creating $SAVEDIR
		mkdir $SAVEDIR
	fi
	cd $SPEAKUPDIR
	DIRLIST=$(find . -type d |sed -e 's/..//' -e '/\./d')
	for d in $DIRLIST; do
		if [ ! -d $SAVEDIR/$d ]; then
			mkdir $SAVEDIR/$d
		fi
	done
	SAVELIST=$(find . -type f |sed 's/..//')
	for f in $SAVELIST; do
		case $f in
			silent|synth*|version)
			;;
			*)
				if [ -r $f -a -w $f ]; then
					cp $f $SAVEDIR/$f
				fi
			;;
		esac
	done
}

usage()
{
	echo "usage: speakupconf load/save [optional directory]"
}

SPEAKUPDIR=/sys/accessibility/speakup
if [ ! -d $SPEAKUPDIR ]; then
	die no directory $SPEAKUPDIR
fi
SYNTH=$(cat $SPEAKUPDIR/synth)
CURRENTDIR=$(pwd)

# After checking for existance of a second parameter, check to see if it
# begins with a / character. If it does, treet it as an absolute
# path; otherwise, prepend the current working directory onto it.
if [ -n "$2" ]; then
	if echo "$2" | grep -q '^/.*' -; then
		SAVEDIR="$2"
	else
		SAVEDIR="$CURRENTDIR/$2"
	fi
elif [ $(id -u) -eq 0 ]; then
	SAVEDIR="/etc/speakup"
else
	SAVEDIR="$HOME/.speakup"
fi

case "$1" in
*load)
	load
;;
*save)
	save
;;
*)
	usage
	exit 1
;;
esac
