#!/usr/bin/env perl

# Shorten a path environment variable by removing duplicates and
# non-existent directories.
# With optional argument "-r REGEXP", removes any matching path element.
# Works for either space- or colon-delimited paths.
# Usage:
#   # csh
#   setenv PATH `echo $PATH | .../plume-scripts/path-remove`
#   # sh
#   export PATH=`echo $PATH | .../plume-scripts/path-remove`
#   ## Does this even work??
#   set path = (`echo $path | .../plume-scripts/path-remove`)

my $debug = 0;
# $debug = 1;

my $extra_regexp;               # undefined if not specified on command line.

while (scalar(@ARGV) > 0) {
  if ($ARGV[0] eq "-r") {
    if (scalar(@ARGV) < 2) {
      die "No regexp specified after -r";
    }
    shift @ARGV;
    $extra_regexp = shift @ARGV;
  } else {
    die "path-remove: Unrecognized argument $ARGV[0]";
  }
}

# All the input lines are merged into a single output path, so the output
# separator is decided once, for the whole output:  a colon if any input line
# contains a colon, otherwise a space if any input line contains a space.
# (Each line is still split according to its own contents.)  Preferring the
# colon guarantees that a mix of colon- and space-separated input lines yields
# a valid colon-separated path rather than a space-separated list in which the
# elements of the colon-separated lines are run together.  The default matters
# only if no input line contains a separator.
$saw_colon = 0;
$saw_space = 0;
@result = ();
while (<>) {
      my @pieces;
      my $linesplitchar;
      chomp;
      if ($_ =~ /:/) {
	$linesplitchar = ":";
	@pieces = split(":");
	$saw_colon = 1;
      } elsif ($_ =~ / /) {
	$linesplitchar = " ";
	@pieces = split(" ");
	$saw_space = 1;
      } else {
	# no separators; assume colon, but don't let this line determine the
	# output separator.
	$linesplitchar = ":";
	@pieces = split(":");
      }
      if ($debug) {
	print STDERR "splitchar: $linesplitchar\n";
	print STDERR "" . scalar(@pieces) . " initial components\n";
	# print STDERR "Input: $_\n";
      }
      foreach $temp (@pieces) {
	if (! -d $temp) { next; }
	if (defined($already_seen{$temp})) { next; }
        if (defined($extra_regexp) && ($temp =~ /$extra_regexp/)) { next; }
        # This directory should appear in the output
        push(@result, $temp);
        $already_seen{$temp} = 1;
      }
}

$splitchar = ($saw_colon || ! $saw_space) ? ":" : " ";

if ($debug) {
  print STDERR "" . scalar(@result) . " final components\n";
  print STDERR "output separator: $splitchar\n";
}

print join($splitchar, @result);
