#!/bin/bash
# SuSEfirewall2-bashhash - hash emulation in bash
# Copyright (C) 2004 SUSE LINUX Products GmbH
#
# Author:     Ludwig Nussel
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
# 
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# isn't that sick?

hashlookup()
{
    local h hmatch key q
    if [ "$1" = "-q" ]; then
	q=1
	shift
    fi
    h="hash_$1"
    key="$2"
    eval hmatch="\$hash_match_$h"

    case "$key" in
	*\ *|*-*|*/*) return 1 ;;
    esac

    eval "case $key in
	$hmatch)
	    [ -z "$q" ] && eval echo '\$hash_key_${h}_$key'
	    return 0
	;;
    esac"
    return 1
}

hashadd()
{
    local h hmatch key val
    h="hash_$1"
    key="$2"
    val="$3"
    eval hmatch="\$hash_match_$h"
    case $key in
	$hmatch) ;;
	*)
	    if [ -z "$hmatch" ]; then
		eval hash_match_$h="\"\$key\""
	    else
		eval hash_match_$h="\"\$hmatch|\$key\""
	    fi
	;;
    esac

    eval hash_key_${h}_$key="\$val"
}

hashallkeys()
{
    local h hmatch i
    h="hash_$1"
    eval hmatch="\$hash_match_$h"
    IFS="|" eval echo "\$hmatch"
}

if [ "$1" = "test" ]; then
    hashadd h "foo" "bar"
    hashadd h "bla" "blub"
    hashadd h "red" "blue"
    hashadd h "green" "yellow"

    for i in ${!hash*}; do
	eval echo \"$i=\$$i\"
    done

    hashlookup h foo || echo foo not in hash
    hashlookup h blue || echo blue not in hash
    hashlookup h green || echo green not in hash
    hashlookup -q h green || echo green not in hash
    hashlookup h "x y" || echo "\"x y\" invalid"
    hashlookup h x-y || echo "x-y invalid"

    echo -n "all keys: "
    hashallkeys h
fi

# vim:sw=4
