#!/bin/sh

THISDIR=`dirname "$0"`
DIRNAME=`realpath "$THISDIR/.."`
PROGNAME=`basename "$0"`

if [ "$1" = '--help' ]; then
    cat 1>&2 <<EOF
Usage: $PROGNAME <l4-directory> [ --clean ]

Copy the distributed packages into the "pkg" hierarchy found within the
specified directory. Also copy the distributed configuration examples into the
"conf" hierarchy.

The indicated directory need not be called "l4", but it must at least have a
"conf" directory and a "pkg" directory inside it.

Specifying --clean removes copied objects.
EOF
    exit 1
fi

# Test for a directory argument and whether it exists.

if [ ! "$1" ] || [ ! -e "$1" ] ; then
    cat 1>&2 <<EOF
Please indicate the l4 directory containing a pkg directory hierarchy.
EOF
    exit 1
fi

# Test for an appropriate directory.

if [ ! -e "$1/pkg" ] ; then
    cat 1>&2 <<EOF
The indicated directory does not appear to contain a pkg directory hierarchy.
EOF
    exit 1
fi

L4DIR=$1

# Copy (or remove) each of the objects.

if [ "$2" = '--clean' ] ; then
    CLEAN=$2
else
    CLEAN=
fi

for OBJTYPE in 'conf' 'pkg' ; do
    OBJDIR=`realpath "$L4DIR"`/$OBJTYPE

    for OBJECT in "$DIRNAME/$OBJTYPE/"* ; do
        OBJNAME=`basename "$OBJECT"`
        ORIGIN=`realpath "$OBJECT"`
        TARGET="$OBJDIR/$OBJNAME"

        if [ "$CLEAN" ] ; then
            if [ -d "$TARGET" ]; then
                rm -r --one-file-system "$TARGET"
            else
                rm "$TARGET"
            fi
        else
            if [ -d "$ORIGIN" ]; then
                cp -R "$ORIGIN" "$TARGET"
            else
                cp "$ORIGIN" "$TARGET"
            fi
        fi
    done
done
