#!/bin/bash
# A script to "page" forwards and back through files of instruction/documentation etc.
# Files are numbered from 1 up as the final character in name e.g. doc1 doc2 , start1 start2 start3
# set -vex
PATH=$PATH:/usr/local/lib/inx
# These variables can be set here, but it's more useful to export them from
# the calling script, since thus you can use this script for a variety of docs etc. (e.g. starter, advanced)

#HEADCOL=yellow                      # Adjust colours and bold to taste,
#TEXTCOL=white                       # as for other variables.
#BOLDNESS=bold
#DOCDIR=/usr/local/share/doc/inx
#DOCSUB=starter                      # The directory where the docs/files live
#HEADFILE=headings
#NUMBER=0
#DOCNAME=start
HEADRANGE=$(wc -l < ${DOCDIR}/${DOCSUB}/${HEADFILE})

. inx_essentials

backforward ()
{
    $BOLDNESS ; $HEADCOL
    echo -e "    Hit \"b\" to go back, \"i\" for an index,  any other key to continue..."
    read -s -n 1 BACKFORWARD
        case $BACKFORWARD in
            b|B)
            NUMBER=$((( $NUMBER - 2 )))
            displaydoc
            ;;
	    i|I)
	    index
	    ;;
            *)
            displaydoc
            ;;
        esac
}

index ()
{
    INDEX=0
    clear
    echo
    $BOLDNESS ; $HEADCOL
    docindex="$(mktemp)"
    echo -e "\n    INDEX\n"
    > $docindex	    
    $TEXTCOL
    for line in $(seq $(( ${HEADRANGE} - 1 )))
      do
        INDEX=$(( $INDEX + 1 ))
	echo "    ${INDEX}:" >> $docindex
      done
    paste $docindex $DOCDIR/$DOCSUB/$HEADFILE 
    $HEADCOL
    echo -e "\n    Please type the number for the section that you want to read, then <enter>.\n"
    $TEXTCOL
    printf "    " ; read "SECTION"
        if [ "$SECTION" -le "$(( $HEADRANGE - 1 ))" ] 2> /dev/null ; then
	        NUMBER=$(( $SECTION - 1 ))
	        displaydoc
        else
            echo -e "\n    That doesn't look like an option... Please try again."
            sleep 4
            index
        fi
}

displayheading ()
{    
    if [ $NUMBER -ge 1 ] ; then
        head -$NUMBER $DOCDIR/$DOCSUB/$HEADFILE | tail -1
    else
        tput sgr0
        exit    
    fi
}    

displaydoc ()
{
    NUMBER=$((( $NUMBER + 1 )))
    if [ $NUMBER -gt $HEADRANGE ] ; then  # We've hit the end of the doc
        tput sgr0
        exit
    fi    
    DOCFILE=${DOCDIR}/${DOCSUB}/${DOCNAME}${NUMBER}
    white ; clear ; echo 
    $BOLDNESS ; $HEADCOL      
    displayheading
    echo
    $BOLDNESS ; $TEXTCOL
    if [ -f ${DOCFILE} ] ; then
        cat ${DOCFILE}
    else
        tput sgr0
        exit 
    fi
    echo
    backforward
}

    displaydoc 
