# !/bin/bash

usage() 
{
    echo " Usage  mank filename(.asciidoc) OR mank -f filename(.asciidoc) [optional -p path -s(cripted)]"
    exit 1
}


## If only one arg, assumed to be name of asciidoc to display
if [[ "$#" -eq 1 && "$1" != "-h" ]]; then
    fil=$1
## otherwise allow use with specific switches and paramenters
else
    TEMP=`getopt -o f:shp: -- "$@"`
    eval set -- "$TEMP"

    while true ; do
	case "$1" in
	    -h) usage ;;
    	    -f)
        	case "$2" in
                    *) fil=$2 ; shift 2 ;;
	        esac ;;
    	    -s) script="yes" ; shift ;;
    	    -p)
        	case "$2" in
                    *) path=$2 ; shift 2 ;;
	        esac ;;

	    --) shift ; break ;;
            *) echo "Internal error!" ; exit 1 ;;
	esac
    done
fi

if [ -z "$fil" ]; then
    usage
fi

if [ ! -f /usr/bin/elinks ]; then
    echo "$0 script requires 'elinks', install it and run again"
    exit 1
fi

if [ ! -f /usr/bin/asciidoctor ]; then
    echo "$0 script requires 'asciidoctor', install it and run again"
    exit 1
fi

# if path supplied use that over defaults
if [ -n "$path" ]; then
    filn=$(find "$path" -type f -name "$fil.asciidoc")
else
    if [ "$RIP" == "yes" ]; then
	filn=$(find . $EMC2_HOME/man /usr/share/doc/machinekit/man -type f -name $fil.asciidoc)
    else
	## this is the install path for machinekit-manual-pages plus optional /local prefix
	filn=$(find . /usr/share/doc/machinekit/man -type f -name $fil.asciidoc)
    fi
fi

if [ ! -z "$filn" ]; then
    asciidoctor $filn -o - | elinks -dump | pager -s

    ## allow dispensing with key read and screen clear when scripting use of mank, as in instcomp / comp
    ## --view-doc

    if [ "$script" != "yes" ]; then
	read -p "Press [Enter] to exit: "
        clear
    fi
else
    echo "Incorrect syntax or file does not exist"
    usage
fi
exit 0


 
