#!/bin/sh
# A script to change the XkbOption "compose" variable in xorg.conf
# Part of the Puppy XkbConfigurator

##--------variables---------->>
INFILE='/etc/X11/xorg.conf'
OUTFILE='/etc/X11/xorg.conf.tmp10'
OPTION='compose'
LIST="/etc/X11/xkb/rules/xorg.lst"
# exported the following from main
#ERRMSG='Xdialog --title "ERROR" --msgbox "An Error has occured! Try again." 0 0'
#SUCCESS='Xdialog --title "Success!" --no-buttons --infobox "Changes applied successfuly!" 0 0 2000'

# the full line containing XkbOptions:
ORIGINAL=`fgrep '"XkbOptions"' $INFILE | grep -v '^#'`

#find current variants and layouts:
CURRENT=`echo "$ORIGINAL" | cut -d'"' -f4`

# check if already have one, find description and add to message.
EXIST=`echo -n "$CURRENT" | tr ',' '\n' | fgrep "$OPTION:"`

if [ ! "$EXIST" = "" ]; then
	INFO=`fgrep -w "$EXIST" $LIST`
	MESSAGE="現在、次のキーポジション設定を使っています:
	"$INFO"

変更するには、下から新しいものを選んで「OK」を押して下さい。
取り外すには、下から選んで「OK」を押して下さい。
中止するには、「Cancel」を押して下さい。"
else
	MESSAGE="使いたい設定を選んで「OK」を押して下さい。
中止するには「Cancel」を押して下さい。"
fi

# give choice dialog
CHOICE=`Xdialog --stdout --title "Xkbオプションの構成" --left --menubox "$MESSAGE" 15 45 10 compose:ralt "右Alt が Compose" compose:rwin "右Win キーが Compose" compose:menu "Menu が Compose" compose:rctrl "右Ctrl が Compose"`
[ ! $? -eq 0 ] && echo "cancelled" && exit 
echo "$CHOICE"

if [ ! "$EXIST" = "" ]; then # if there's one already
	if [ "$CHOICE" = "$EXIST" ]; then # the same -> remove
		NEW=`echo -n $CURRENT | tr ',' '\n' | fgrep -v $CHOICE | tr '\n' ',' | tr -s ',' | sed 's/^,//;s/,$//'`
	else # change
		NEW=`echo "$CURRENT" | sed "s/$EXIST/$CHOICE/"`
	fi
else
	NEW="$CURRENT,$CHOICE"
	[ "$CURRENT" = "" ] && NEW="$CHOICE"
fi

# add new variant to line, or entire line, if it doesn't exist:
if [ "$ORIGINAL" = "" ] ;then
	ORIGINAL=`fgrep '"XkbVariant"' $INFILE | grep -v '^#'`
	[ "$ORIGINAL" = "" ] && ORIGINAL=`fgrep '"XkbLayout"' $INFILE | grep -v '^#'`
	MODIFIED="$ORIGINAL\n	Option 		\"XkbOptions\"   \"$NEW\""
else
	MODIFIED=`echo "$ORIGINAL" | sed "s%\"$CURRENT\"%\"$NEW\"%"`
fi

# add to file
cat $INFILE | sed "s%$ORIGINAL%$MODIFIED%" >$OUTFILE

if ! fgrep -q '"XkbOptions"' $OUTFILE ;then
	eval $ERRMSG
	rm -f $OUTFILE
else
	mv -f $OUTFILE $INFILE
	eval $SUCCESS
fi
exit