#!/bin/sh

show_usage ()
{
    echo ""
    echo "Usage: `basename $0` <documentFormat>"
    echo ""
    echo "  where <documentFormat> can be one of the following:"
    echo ""
    print_available_formats
    echo ""
    exit 0
}

#-------------------------------------------------------------

locate_pod_converter()
{
    podType=${1:-man}
    podPgm=`where_is -f pod2$podType`

    if [ "$podPgm" = "" ]; then
        status=1  # failed to find converter
    else
        podPgmDir=`dirname $podPgm`
        status=0
    fi
    
    return $status
}

#-------------------------------------------------------------

print_available_formats ()
{
    locate_pod_converter
    
    if [ "$?" = "1" ]; then
        echo "** Cannot find any pod conversion programs!"
        echo "     Where are pod2man, pod2text, etc. located?"
        echo "     Update PATH environment with pod conversion directory."
    else
        podConversionPgms=`cd $podPgmDir; ls pod2*`
        availableFormats=`echo $podConversionPgms|/bin/sed -e "s/pod2//g"`
        echo "    $availableFormats"
    fi
}

#------------------------------------------------------------- 

# Cannot use this documentation generator, until 
# the 'where_is' program has already been built.

ignore=`where_is where_is 2>&1`
if [ $? -eq 1 ]; then
    echo ""
    echo "** Cannot generate documentation until 'where_is' program"
    echo "   is made available. (build expander package first)"
    echo "   Make sure where_is can be seen through PATH setting."
    echo""
    exit 1
fi

if [ "$1" = "" ]; then
    show_usage
fi

podSource=`ls *.pod`
format=${1:-text}    # the default format is text.

#---------------------
# Protect our behinds. 
#---------------------
if [ "$format" = "pod" ]; then
    echo "** This will overwrite the source, and is not allowed!"
    exit 1
fi

locate_pod_converter $format

if [ "$?" = "1" ]; then
    echo "** Specified format ($format) has no pod converter."
else
    #-------------------------------------------------
    # Convert all the pod documents to the new format.
    #-------------------------------------------------
    for file in $podSource; do
        docName=`echo $file|/bin/sed -e "s/\..*$//"`
        case $format in
          latex) pod2$format $file > $docName.tex  ;;
            man) pod2$format -c "Text Filters" -r " " $file > $docName.1  ;;
           text) pod2$format $file > $docName.txt  ;;
           html) pod2$format --title "NEdit Utilities" $file > $docName.html ;;
              *) pod2$format $file > $docName.$format ;;
        esac
    done
fi

