#!/bin/sh
# https://idiomdrottning.org/tldr-to-man
# requires pandoc


# For each tldr file in the current directory when you call
# tldr_to_man.sh, it checks if you have that program installed (using
# which).

# As command line options, add any files that you want installed even if
# you don't have matching program installed.

# For example, in pages/common I ran it with tldr_to_man.sh git-* and in
# pages/linux I just ran tldr_to_man.sh

# If you do, it formats it into a man page and places it in
# /tmp/tldrmanpages that you can later move to your systems man page
# directory, for example /usr/local/share/man/man5/, as root. Use cp -n
# when copying them so you don't clobber any real man pages.

# And then you can view them with man 5 ffmpeg or whatever.

commandsplit () {
    command -v "$(echo -n "$*" | sed 's/[-.].*$//')" > /dev/null||
    command -v "$(echo " $*" | sed 's/[-.].*$//')" > /dev/null
}

tldrprepare () {
    echo "% $(head -1 "$1"|cut -c3-|tr '[:lower:]' '[:upper:]') (5)"
    echo % The TLDR project
    date +%%\ %B\ %Y
    cat "$1"
}

tldrize () {
    mkdir -p /tmp/tldrmanpages
    page="$1"
    tldrprepare "$page"| pandoc -f markdown -t man -s |sed -e 's/{{/\\f[B]/g' -e 's/}}/\\f[R]/g'  | gzip -9c > /tmp/tldrmanpages/"$(basename "$page" .md)".5.gz
}

for page in *.md
do
    $(commandsplit "$page") && tldrize "$page"
done

for page in "$@"
do
    tldrize "p$page"
done

