#
# Prepare build subdirectory for module
#
# SPDX-FileType: SOURCE
# SPDX-FileCopyrightText: Michael Bäuerle
# SPDX-License-Identifier: BSD-2-Clause
#
# Must be called with the module name as parameter.
#

# Abort after error
set -e

# Enforce POSIX locale
LC_ALL=POSIX
export LC_ALL

# Check environment and parameter
if test "x" = "x$1"
then
    printf '%s\n' 'Must be called with module name as parameter'
    exit 1
else
    PMBS_MODULE=$1
fi

# Prepare module subdirectory
mkdir -p "$PMBS_MODULE"
for pn in ../$PMBS_MODULE/*
do
    # Do nothing if there was no filename expansion
    if test "$pn" != "../$PMBS_MODULE/*"
    then
        # "Build.mk" needs special handling (see below)
        if test "$pn" != "../$PMBS_MODULE/Build.mk"
        then
            # Extract filename from pathname
            file=$(basename "$pn")
            # Create symlinks to module directory
            if ! test -e "$PMBS_MODULE/$file"
            then
                ln -s "../$pn" "$PMBS_MODULE/$file"
            fi
        fi
    fi
done

# Assemble Makefile from global configuration header and module torso
if test -e "../$PMBS_MODULE/Build.mk"
then
    cat "../pmbs/Config.mk" "../$PMBS_MODULE/Build.mk" >"$PMBS_MODULE/build.mk"
fi
