#!/usr/bin/perl -wT

use CGI;
use lib ( '.' );
use lib ( '../lib' );
use TWiki;
use strict;

&main();

sub writeDebug {
 open D, ">>/var/tmp/dbg.txt";
 print D $_[0];
 close D;
}

sub getSearchType {
 my $type = shift;
 my ($action, $qfield, @hfields, @fulltext, $line, $proc);
 my ($meta, $text) = &TWiki::Store::readTopic("TWiki", "MultiSearch");
 $text = &TWiki::handleCommonTags($text, "MultiSearch");
 @fulltext = split /\n|\r\n/, $text;
 
 $proc = 0;
 foreach $line (@fulltext) {
  # writeDebug("Line: $line\n");
  if ($line =~ m/\* $type/gi) {
   $proc = 1;
   next;
  }
  
  if ($proc == 1) {
   if ($line =~ m/\* Action: (.*)/gi)       { $action = $1; }
   elsif ($line =~ m/\* Query field: (.*)/gi)  { $qfield = $1; }
   elsif ($line =~ m/\* Hidden field: (.*)/gi) { push @hfields, $1; }
   elsif ($line =~ m/\* (.*)/g)                { last; }
  }
 }
 
 return ($action, $qfield, @hfields);
}

sub main {
 my $query = new CGI;
 my $stype = $query->param('type');
 my $terms = $query->param('query');
 my ($action, $qfield, @hfields) = &getSearchType($stype);
 
 die "Can't get search type info for $stype" if !$action;
 
 my $url = $action . "?" . $qfield . "=" . $terms;
 foreach my $hidden (@hfields) { $url .= "&" . $hidden; }
 print $query->redirect($url);
}

1;
