#!/bin/bash
#
# Usage:	mktree base dir cmd...
#
#       where	base	is the base directory for the tree to be created,
#		dir	is the path in the said tree, and
#		cmd	is one or more commands to be placed there.
#
###############################################################################
#
# Analyse the number of parameters supplied.

if [ $# -lt 2 ]; then
    echo Usage: `basename "$0"` base dir '[cmd]...' >&2
    exit 255
fi

if [ $# -eq 2 ]; then
    exit 0			# Empty command list - NOT an error.
fi

###############################################################################
#
# Specify the directories to use.

DIR=`echo "$1"/"$2" | tr -s / | sed 's=/$=='`
MAN=`echo "$1"/usr/man | tr -s /`
shift 2

###############################################################################
#
# Check they're not non-directories.

if [ -e "${DIR}" -a ! -d "${DIR}" ]; then
    printf '%s: ERROR 1: Not a directory: %s\n' >&2 \
		`basename "$0"` "${DIR}"
    exit 1
fi
if [ "${DIR}" = "${MAN}" ]; then
    for THIS in "${MAN}"/man{1,2,3,4,5,6,7,8,9,n} ; do
	if [ -e "${THIS}" -a ! -d "${THIS}" ]; then
	    printf '%s: ERROR 2: Not a directory: %s\n' >&2 \
			`basename "$0"` "${THIS}"
	    exit 2
	fi
    done
fi

###############################################################################
#
# Ensure the target directory exists.

mkdir -p "${DIR}"

###############################################################################
#
# Function to determine if a particular command has been copied across.

function needed() {
    local X=`echo "$2" | rev | cut -b 3- | rev`

    find $1/../.. -name "$X" > /dev/null
}

###############################################################################
#
# Copy the commands as listed.

if [ "${DIR}" != "${MAN}" ]; then
    for FILE do
	if [ -f "${FILE}" ]; then
	    cp -fv "${FILE}" "${DIR}"/
	else
	    printf '%s: WARNING: Skipping missing command: %s\n' >&2 \
		`basename "$0"` "${FILE}"
	fi
    done
else
    for FILE do
	if [ -f "${FILE}" ]; then
	    SUB=`echo "${FILE}" | rev | cut -b 1`
	    if [ ! -e "${MAN}"/"man${SUB}" ]; then
		mkdir "${MAN}"/"man${SUB}"
	    fi
	    cp -fv "${FILE}" "${MAN}"/"man${SUB}"/
	else
	    printf '%s: WARNING: Skipping missing manual page: %s\n' >&2 \
		`basename "$0"` "${FILE}"
	fi
    done
fi

###############################################################################
#
# Finished.

echo 'Finished - at last!!'

###############################################################################
# EOF #
#######
