#!/bin/sh

set -e

EXAMPLE_TEMP=$1
DOC_DIR=$2
VERSION=$3

move_examples()
{
	local pkgName=$1
	local pkgContent=$2
    # Make examples dir
    install -d -m 755 ${DOC_DIR}/${pkgName}/${VERSION}/examples
    for package in ${pkgContent}
    do
        EXAMPLE_TEMP_DIR="$EXAMPLE_TEMP/${package}/examples"
        if [ -d "$EXAMPLE_TEMP_DIR" ]; then
            echo "Moving examples of ${package}"
            EXAMPLE_INSTALL_DIR="${DOC_DIR}/${pkgName}/${VERSION}/examples/${package}"
            # Move dir renaming it
            if [ -e "${EXAMPLE_INSTALL_DIR}" ]
            then
                echo "#### \"${EXAMPLE_INSTALL_DIR}\" is in the way, please remove it first ####"
                exit 255
            else
                mv -v -f "${EXAMPLE_TEMP_DIR}" "${EXAMPLE_INSTALL_DIR}"
                # Remove empty directories:
                rmdir --ignore-fail-on-non-empty "${EXAMPLE_INSTALL_DIR}"
            fi
        fi
        DOC_TEMP_DIR="$EXAMPLE_TEMP/${package}"
        if [ -d "$DOC_TEMP_DIR" ]; then
            echo "Moving documentation of ${package}"
            DOC_INSTALL_DIR="${DOC_DIR}/${pkgName}/${VERSION}/${package}"
            # Move dir renaming it
            if [ -e "${DOC_INSTALL_DIR}" ]
            then
                echo "#### \"${DOC_INSTALL_DIR}\" is in the way, please remove it first ####"
                exit 255
            else
                mv -v -f "${DOC_TEMP_DIR}" "${DOC_INSTALL_DIR}"
                # Remove empty directories:
                rmdir --ignore-fail-on-non-empty "${DOC_INSTALL_DIR}"
            fi
        fi
    done

    # Remove empty directories:
    rmdir --parents --ignore-fail-on-non-empty ${DOC_DIR}/${pkgName}/${VERSION}/examples
}

echo '**** Copying examples ****'
PACKAGE_LIST='debian/'*'.install.in'

for PACKAGE_FILE in ${PACKAGE_LIST}
do
    PACKAGE_NAME=`basename "${PACKAGE_FILE}" '.install.in'`
    PACKAGE_CONTENT=`grep 'usr/lib/${DEB_HOST_MULTIARCH}/fpc' "${PACKAGE_FILE}" | awk '{print $1}' | sed -e 's@.*/\([^/]\)@\1@' | sed -e 's/\*//'`
	echo '    **** PACKAGE_NAME = "'${PACKAGE_NAME}'"'
	echo '    **** PACKAGE_CONTENT = "'${PACKAGE_CONTENT}'"'
    move_examples "${PACKAGE_NAME}" "${PACKAGE_CONTENT}"
done

echo '**** Examples copied ****'

if [ -d $EXAMPLE_TEMP ] ; then
    echo "Example dir should be empty now or the rmdir command will fail, showing current content follows:"
    ls -al $EXAMPLE_TEMP
    rmdir $EXAMPLE_TEMP
fi
