#!/bin/bash
#
# Redirect commands from pipe A to pipe B and C
#

set -e
set -u

ICINGA_CMD=${1:-"/usr/local/icinga/var/rw/icinga.cmd"}
ICINGA_MYSQL_CMD=${2:-"/usr/local/icinga-mysql/var/rw/icinga.cmd"}
ICINGA_PGSQL_CMD=${3:-"/usr/local/icinga-pgsql/var/rw/icinga.cmd"}

trap 'rm -f "$ICINGA_CMD"; exit' EXIT SIGKILL

if [[ -p "$ICINGA_CMD" ]]; then
    rm -f "$ICINGA_CMD"
fi

mkfifo -m 660 "$ICINGA_CMD"
chown icinga.icinga-cmd "$ICINGA_CMD"

while true
do
    if read COMMAND
    then
        if [[ -p "$ICINGA_MYSQL_CMD" ]]; then
            echo "$COMMAND" > "$ICINGA_MYSQL_CMD"
        else
            logger -p local0.err Can\'t distribute command to the Icinga MySQL instance since its command pipe doesn\'t exist
        fi
        if [[ -p "$ICINGA_PGSQL_CMD" ]]; then
            echo "$COMMAND" > "$ICINGA_PGSQL_CMD"
        else
            logger -p local0.err Can\'t distribute command to the Icinga PostgreSQL  instance since its command pipe doesn\'t exist
        fi
    fi
done < "$ICINGA_CMD" 3> "$ICINGA_CMD"

# Reset all traps
trap - EXIT SIGKILL

exit 0
