#!/bin/csh -f

# Removes redundant and nonexistent directories from a path and
# returns the result (to be assigned to an environment variable by the
# caller.  A distinction is made between absolute and relative
# directories.  Absolute directories must exist, but relative
# directories are only removed if they are redundant.

# The input path can be derived from a single argument or many; each
# argument may be further composed of directories separated by white
# space or colons, but directories cannot contain colons, and but the
# resulting list of directories is returned colon-separated.  The
# directory names can contain quoted shell metacharacters and globbing
# will be done in the context of each directory on the search path.
# Some programs make use of null path-entries in special ways.  This
# script checks for such entries (: at beginning : at end or double ::
# in the middle) and represents such an entry internally and in
# diagnostic messages as _NULL_

# Watch out for bad aliases if working with default .cshrc from the
# department, e.g., aliasing of ls to include "| more".

# Watch out for "Word too long" if trying to just give "path" argument;
# May need to break up into separate directories as separate arguments.

set tempmsgs = /tmp/cleanpath.msgs.$user.$$
set templs = /tmp/cleanpath.ls.$user.$$
set tempdirs = /tmp/cleanpath.dirs.$user.$$
\rm -f $templs $tempdirs $tempmsgs
touch $templs $tempmsgs $tempdirs

if ($#argv < 1) echo 'Usage: cleanpath path OR cleanpath dir ...' >>$tempmsgs


set noglob

set pathtoclean = (`echo $* | sed  -e 's+^:+_NULL_:+' -e 's+:$+:_NULL_+' -e 's+::+:_NULL_:+g' | tr ':' ' '`)

unset noglob

foreach dir ($pathtoclean)
  switch ($dir)
  case /*:
    if (-d $dir) then
      \ls -idL $dir >> $templs
    else
      echo $dir does not exist. >>$tempmsgs
    endif
    breaksw
  default:
    echo "0 $dir" >> $templs
  endsw
end

awk '{if ($1 == 0)\
         if (nameseen[$2] != "") print $2, "already in path" >>"'$tempmsgs'"\
         else {\
               print $2 > "'$tempdirs'"\
               nameseen[$2] = "yes"\
               }\
      else\
         if (inumseen[$1] != "") print $2, "already in path as", inumseen[$1] >> "'$tempmsgs'"\
         else {\
               print $2 > "'$tempdirs'"\
               inumseen[$1] = $2\
               }\
     }' $templs

cat $tempdirs | tr '\012' : | sed -e 's+_NULL_++' -e 's+:$++'

tty -s
if (! $status) then
   cat $tempmsgs > `tty`
endif

\rm -f $templs $tempdirs $tempmsgs
