#!/bin/bash -e

#
# Wrapper around llama-cli to massage the output to be more palatable to
# help2man for generating a manual page.
#
# Invoke as:
#   gen-manpage build/bin/llama-cli --name='LLM inference in C/C++'
#
# This script is in the public domain and may be distributed or modified
# without restriction.
#

: ${HELP2MAN:=help2man}

tmp=$(mktemp -d)
trap "rm -rf $tmp" EXIT HUP INT

cmd="${1?}"
shift

# --version goes to stderr?
$cmd --version 2>$tmp/version

# --help to stdout, some diagnostics to stderr
$cmd --help    >$tmp/help 2>/dev/null

# Ensure we got something from both.
test -s $tmp/version && test -s $tmp/help

cmd="${cmd##*/}"

# Strip out just version.
sed -i -n "s/^version: /$cmd /p" $tmp/version

# Convert ---thing--- to subheadings, and clean up args.
sed -i \
    -e 's/^----- \([A-Za-z].*\) -----/\1:/' \
    -e 's/^[a-z].*:$/\u&/' \
    -e '/^[A-Za-z].*:$/s/ [a-z]/\U&/g' \
    -e 's/^-\(-\?[a-zA-Z0-9][^ ]*,\)\( *\)\(-.*\)  /-\1 \3\2 /' \
    -e 's/^-\(.*\)   / -\1  /' \
    -e '/  *[^ ].*: [^ ]/s/:/:  /' \
    $tmp/help

cat <<EOT >$tmp/${cmd##*/}
#!/bin/bash

for arg; do
  case "\$arg" in
  --version) cat $tmp/version;;
  --help)    cat $tmp/help;;
  esac
done
EOT

chmod a+x "$tmp/$cmd"
${HELP2MAN} --no-info "$@" "$tmp/$cmd"

exit $?
