1#!/usr/local/bin/perl
2#
3# Chain multiple redirectors together.
4#	- Cameron Simpson <cs@zip.com.au>
5#
6
7use strict vars;
8
9use IO::File;
10use IPC::Open2;
11
12die "Usage: $0 redirectors...\n" if ! @ARGV;
13
14## Note that the ZAP_CHAINING variable is obsolete these days.
15## - Cameron Simpson <cs@zip.com.au> 17jul2001
16##
17##$::Chaining = ( length $ENV{ZAP_CHAINING}
18##	      ? $ENV{ZAP_CHAINING} eq 'FULL'
19##		? 2
20##		: 1
21##	      : 0
22##	      );
23$::Chaining = 0;
24
25my @sub=();
26my $nsubs=0;
27
28for my $sub (@ARGV)
29{
30  ++$nsubs;
31
32  my $rd = "RD$nsubs";
33  my $wr = "WR$nsubs";
34  my $pid = open2($rd, $wr, $sub);
35  die "$0: can't open2($sub): $!\n" if ! defined $pid;
36
37  autoflush $wr 1;
38
39  push(@sub,[$sub,$pid,$rd,$wr]);
40}
41
42autoflush STDOUT 1;
43
44my @words;
45my $o_;
46my $redir;
47my($sub,$pid,$rd,$wr);
48
49while (defined($_=<STDIN>))
50{ chomp;
51
52  @words = split;
53  $o_ = $_;
54
55  # pass through every redirector
56  for my $s (@sub)
57  { ($sub,$pid,$rd,$wr)=@$s;
58
59    print $wr $_, "\n";
60
61    $redir=<$rd>;
62    die "$0: unexpected EOF from [$sub]" if ! defined $redir;
63    chomp($redir);
64
65    if (length($redir))
66    # redirected
67    { my @nwords=split(/\s+/,$redir);
68
69      if (@nwords == 1)
70      # plain URL
71      { $words[0]=$nwords[0];
72      }
73      else
74      # full redirector input line
75      {
76	if (@nwords != 4)
77	{ warn "$0: @words -> @nwords";
78	}
79
80	@words=@nwords;
81      }
82
83      $_="@words";
84    }
85  }
86
87  if ($::Chaining == 0)
88  # pure redirector
89  { print STDOUT (($_ eq $o_) ? '' : $words[0]), "\n";
90  }
91  elsif ($::Chaining == 1)
92  # print new URL;
93  { print STDOUT $words[0], "\n";
94  }
95  else
96  { print STDOUT $_, "\n";
97  }
98}
99
100exit 0;
101