#!/bin/bash

Version=2.03
Myname="${0##*/}"

doc=$(cat \
<<'DOC'
= paths - list the current PATH, MANPATH and INFOPATH, marking doubles

= Synopsis
paths [-c]	

= Options
-h,--help	print this help and exit
-H,--Help	print full documentation via less and exit
-V,--version	print version and exit

= Description
paths displays the contents of |$PATH|, |$MANPATH| and |$INFOPATH|, listing each directory
on a separate line and marking duplicates.

For example:
   $ paths
   PATH:
     /home/wybo/bin
     /usr/local/texlive/2011/bin/i386-linux/
     /usr/local/sbin
     /usr/local/bin
     /usr/sbin
     /usr/bin
     /sbin
     /bin
     /usr/games
   MANPATH:
     ./man
     /usr/local/man
     /usr/local/texlive/2011/texmf/doc/man
   INFOPATH:
     /usr/local/texlive/2011/texmf/doc/info

Directories that occur more than once in the path will be marked with asterisks, for example:
   $ PATH=/local/bin:$PATH paths
   PATH:
   **/local/bin
     /home/wybo/bin
   **/local/bin
     /usr/local/texlive/2011/bin/i386-linux/
     /usr/local/sbin
     ...

= Author
[Wybo Dekker](wybodekker@me.com)

= Copyright
Released under the [GNU General Public License](www.gnu.org/copyleft/gpl.html)
DOC
)

# --- colors, help from embedded doc, die ---
[ -t 1 ] && { Red=$'\e[1;31m' Nor=$'\e[0m'; } || Red='' Nor=''
nv="-$Myname-${Version/./\\.} (press h for help, q to quit)"
helpsrt() { sed -n '/^= Synopsis/,/^= Desc/{//d;p}' <<<"$doc"; exit; }
helpall() { less -P"$nv" <<<"$doc"; exit; }
    die() { printf "%s$Nor\n" "${@/#/$Myname: $Red}" >&2; exit 1; }

:<<'DOC' #----------------------------------------------------------------------
= handle_options
synopsis:	 handle_options "$@"
description:	handle the options.
globals used:	 Myname Version
globals  set:	 args
DOC
#-------------------------------------------------------------------------------
handle_options() {
   local options
   options=$(getopt \
      -n "$Myname" \
      -o hHIV \
      -l help,Help,version -- "$@"
   ) || exit 1
   eval set -- "$options"
   while [ $# -gt 0 ]; do
      case $1 in
      (-h|--help)    # print this help and exit
		     helpsrt
		     ;;
      (-H|--Help)    # print full documentation via less and exit
		     helpall
		     ;;
      (-V|--version) # print version and exit
		     echo $Version
		     exit
		     ;;
      (-I)	     instscript "$0" ||
			die 'the -I option is for developers only'
		     exit
		     ;;
      (--)	     shift
		     break
		     ;;
      (*)	     break
		     ;;
      esac
   done
   args=( "$@" )
}

handle_options "$@"
set -- "${args[@]}"

for i in PATH MANPATH INFOPATH; do
   declare -A n
   echo $i:
   eval P="\${$i//::/:}"
   IFS=: read -ra entries <<<"$P"
   for p in "${entries[@]}"; do 
      (( n[$p]++ ))
   done
   for p in "${entries[@]}"; do
      if (( n[$p] >1 )); then
         echo '**' "$p"
      else
         echo '  ' "$p"
      fi
   done
done
