#!/bin/sh

DIRNAME=`dirname "$0"`
PROGNAME=`basename "$0"`

if [ "$1" = '--help' ] || [ ! "$1" ] || [ ! "$2" ]; then
    cat 1>&2 <<EOF
Usage: $PROGNAME <definitions file> <output directory> [ <configuration> ]

Produce files to configure imip-agent using the definitions in the specified
file, storing the configuration files in the given output directory. This
utility is intended to make the customisation of the example configuration files
easier.

Once the files have been generated, they may be reviewed and copied into the
appropriate locations.
EOF
    exit 1
fi

DEFSFILE=$1
OUTDIR=$2
CONF=${3:-"conf"}

if [ ! -e "$DEFSFILE" ]; then
    cat 1>&2 <<EOF
The specified definitions file $DEFSFILE does not exist.
EOF
    exit 1
fi

if [ ! -e "$CONF" ]; then
    cat 1>&2 <<EOF
The conf directory cannot be found.
EOF
    exit 1
fi

# Obtain the definitions.

. "$DEFSFILE"

# Configure the components.

for COMPONENT in apache exim postfix ; do
    CONFDIR="$CONF/$COMPONENT"

    for FILENAME in `find "$CONFDIR" -type f` ; do
        PARENT="$OUTDIR/"`dirname "$FILENAME"`
        if [ ! -e "$PARENT" ]; then
            mkdir -p "$PARENT"
        fi
        
        envsubst "$SUBSTITUTED" < "$FILENAME" > "$OUTDIR/$FILENAME"
    done
done
