#!/bin/sh -e

binDir="$1"
debianDir="$2"

cd ${binDir}

manPage="${debianDir}/topp.1"
debianLinksFile="${debianDir}/topp.links"

# Start fresh
rm -f ${debianLinksFile}

# List all files in here, but not the Tutorial* binaries.
# Add a dot to the end of each line, where missing.

# First cat the top part of the man page to a temp file

cat ${debianDir}/topp.1-top-skel > ${manPage}

# Now make the one-liners appear after the top.  Note that each time a
# new binary is dealt with, we create a corresponding link in
# ${debianLinksFile}, as each binary must have a corresponding man page.

# Make sure we set a collation order so that it does not vary depending on the
# systems the package is built (this ensure reproducible builds). 
# See https://tests.reproducible-builds.org/debian/issues/collation_order_varies_by_locale_issue.html
# And the report for the reproducible build failure.
#
#
# Comments: 	readdir() order dependency:
# https://sources.debian.net/src/openms/2.0.0-4/debian/binaries-extract-one-line-man-desc.sh/#L24-L29
#
# The «*» on the find(1) command line may introduce a locale dependency (shell
# globs are expanded in a locale-sensitive sorted order), depending on the names
# of immediate children of ${binDir} (to which the script cd's).

LC_COLLATE=C.UTF-8
export LC_COLLATE

for file in $(find * -type f -executable -print | grep -v ^Tutorial)
do
    # The man page itself
    oneLiner=$(./$file --help 2>&1 | grep "${file} --" | sed "s|\([^\.]$\)|\1.|g")
    formattedOneLiner=$(echo "${oneLiner}" | sed 's|\(^[[:alnum:]]\+\)|\\\\fB\1\\\\fR|g')
    echo ${formattedOneLiner} >> ${manPage}
    echo "" >> ${manPage}

    # The symbolic link
    echo "usr/share/man/man1/topp.1 usr/share/man/man1/${file}.1" >> ${debianLinksFile}
done

# Finally make the bottom of the page.

cat ${debianDir}/topp.1-bottom-skel >> ${manPage}

cd - > /dev/null 2>&1
