#!/bin/sh

# ledcontrol (ledcontrol) version 0.5.2
# Copyright (C) 2000 by Sampo Niskanen, distributed under the terms
# of the GNU GPL version 2 or later. ABSOLUTELY NO WARRANTY.
# See the file COPYING for details.

# Requires the programs test, grep, mawk
PATH=/bin:/usr/bin:/usr/local/bin

VERSION="0.5.2"
PACKAGE="ledcontrol"
CONFFILE="/etc/ledd.conf"
READDEFAULT=yes
PIPEFILES=

while test $# -gt 0; do
    case "$1" in
	-h|-help|--help)
	    cat 1>&2 <<HERE
ledcontrol ($PACKAGE) version $VERSION
Copyright (C) 2000 by Sampo Niskanen, distributed under the terms
of the GNU GPL version 2 or later. ABSOLUTELY NO WARRANTY.
See the file COPYING for details.

Usage: $0 [options] [command]

   -h        --help          This help message.
   -v   -V   --version       Print version information.
   -c FILE   --config FILE   Read pipe location from configuration file FILE.
   -p FILE   --pipe FILE     Use FILE as the command pipe.

If -c of -p is not specified, ledcontrol tries to read the pipe location
from the default configuration file [$CONFFILE].
For more information on the format of command, see the documentation.

HERE
	    exit 0;;
	-v|-V|-version|--version)
	    echo "ledcontrol ($PACKAGE) $VERSION" 1>&2
	    exit 0;;
	-c|-config|--config)
	    if test $# -lt 2; then
		echo $0: option $1 requires argument. 1>&2
		exit 1
	    fi
	    if test ! -r "$2"; then
		echo $0: unable to read $2. 1>&2
		exit 1
	    fi
	    NEWPIPES=`grep -i "^[[:space:]]*pipefile[[:space:]]*[^[:space:]][^[:space:]]*[[:space:]]*$" "$2" | mawk '{ print $2 }'`
	    PIPEFILES="$NEWPIPES $PIPEFILES"
	    READDEFAULT=no
	    shift 2;;
	-p|-pipe|--pipe)
	    if test $# -lt 2; then
		echo $0: option $1 requires argument. 1>&2
		exit 1
	    fi
	    PIPEFILES="$2 $PIPEFILES"
	    READDEFAULT=no
	    shift 2;;
	anim|set|nop)
	    break;;
	*)
	    if test -n "`echo "$1" | grep "^ *\(set\|anim\|nop\) "`"; then
		break;
	    fi
	    echo $0: bad option $1. 1>&2
	    exit 1;;
    esac
done

if test $# -lt 1; then
    echo $0: nothing to output. 1>&2
    exit 1
fi

if test $READDEFAULT = yes; then
    NEWPIPES=`grep -i "^[[:space:]]*pipefile[[:space:]]*[^[:space:]][^[:space:]]*[[:space:]]*$" "$CONFFILE" | mawk '{ print $2 }'`
    PIPEFILES="$NEWPIPES $PIPEFILES"
fi

# Find a suitable pipe
for PIPE in $PIPEFILES NOPIPE ; do
    if test -p "$PIPE" -a -w "$PIPE"; then
	break;
    fi
done

if test "$PIPE" = "NOPIPE" ; then
    echo $0: no suitable pipefile found. 1>&2
    exit 1
fi

echo $* >"$PIPE"

