#!/bin/bash
#< Select a random man page

THISPROG=$( basename $0 )
TMPFILE="/tmp/${THISPROG}.$$"

trap 'rm -f ${TMPFILE}; exit 1' 1 2 3 15

# Define sections from which we want to view manual pages
SECTIONS="1 8"
MANBASE="/usr/share/man"

# Generate temporary file containing list of manual pages
# available from selected sections

for SECTION in ${SECTIONS}; do
   cd ${MANBASE}/man${SECTION} 2>/dev/null || {
      echo "Warning: Manual section ${SECTION} does not exist" >&2
   }
   ls -1 | sed 's/^\(.*\)\..*\.gz/\1/' >> ${TMPFILE}
done

# Generate random number between 1 and total number of
# available manual pages
WRDLN=$( wc -l ${TMPFILE} | awk '{ print $1}' )
RNDM=$( awk -v l=$WRDLN 'BEGIN { srand(); 
                                 r = rand() * l; 
                                 printf( "%d", ( r + 1 ) ) }' )

tput clear
man `sed -n "${RNDM}p" ${TMPFILE}`

rm -f ${TMPFILE}
exit 0