#!/bin/sh
# -*- mode: shell-script; coding: utf-8 -*-
#
# add-gnome-keyboard-shortcut
#
# Script to add a a custom shortcut to GNOME Keyboard Shortcuts.
#
# Copyright (C) 2010,2011 Elmar Hoffmann
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

set -e

if [ $# -ne 3 ]; then
    echo "Usage: $(basename "$0") NAME ACTION BINDING"
    exit 2
fi

name="$1"
action="$2"
binding="$3"


dirs=$(gconftool-2 --all-dirs /desktop/gnome/keybindings \
    | sed --quiet \
    --expression='s,^[[:space:]]\+\([^[:space:]]\+/custom[0-9]\+\),\1,gp')

for dir in ${dirs}; do
    if [ "$(gconftool-2 --get-type "${dir}/name")" = 'string' \
	-a "$(gconftool-2 --get "${dir}/name")" = "${name}" ]
    then
	exit 0
    fi
done

if [ -n "${dirs}" ]; then
    last=$(echo "${dirs}" | sort | sed --quiet --expression='$s/^custom//gp')
    next=$(expr "${last}" '+' '1')
else
    next='0'
fi
dir="/desktop/gnome/keybindings/custom${next}"
gconftool-2 --set "${dir}/name" --type string "${name}"
gconftool-2 --set "${dir}/action" --type string "${action}"
gconftool-2 --set "${dir}/binding" --type string "${binding}"
