#!/usr/local/bin/perl
# search_user.cgi
# Ask the LDAP server to return users matching some query

require './ldap-useradmin-lib.pl';
&ReadParse();

# Do the search
$ldap = &ldap_connect();
$base = &get_user_base();
if ($in{'match'} == 0) {
	$search = "($in{'field'}=$in{'what'})";
	}
elsif ($in{'match'} == 1) {
	$search = "($in{'field'}=*$in{'what'}*)";
	}
elsif ($in{'match'} == 2) {
	$search = "(!($in{'field'}=$in{'what'}))";
	}
elsif ($in{'match'} == 3) {
	$search = "(!($in{'field'}=*$in{'what'}*))";
	}
$rv = $ldap->search(base => $base,
		    filter => "(&(objectClass=posixAccount)$search)");
if ($rv->code) {
	&error(&text('search_err', "<tt>$search</tt>",
		     "<tt>$base</tt>", $rv->error));
	}
@users = $rv->all_entries;
if ($rv->count == 1) {
	# If one result, go direct to that user
	&redirect("edit_user.cgi?dn=".&urlize($users[0]->dn()));
	}
else {
	# List matching users
	&ui_print_header(undef, $text{'search_title'}, "");
	if (@users == 0) {
		print "<p><b>$text{'search_notfound'}</b>.<p>\n";
		}
	else {
		print "<table border width=100%>\n";
		print "<tr $tb> <td><b>$text{'user'}</b></td> ",
		      "<td><b>$text{'uid'}</b></td> ",
		      "<td><b>$text{'real'}</b></td> ",
		      "<td><b>$text{'home'}</b></td> ",
		      "<td><b>$text{'shell'}</b></td> ",
		      "<td><b>$text{'index_samba'}</b></td> ",
		      "<td><b>$text{'index_cyrus'}</b></td> </tr>\n";
		foreach $u (sort { lc($a->dn()) cmp lc($b->dn()) } @users) {
			%classes = map { $_, 1 } $u->get_value("objectClass");
			print "<tr $cb>\n";
			print "<td><a href='edit_user.cgi?dn=",
				&urlize($u->dn()),"'>",
				$u->get_value('uid'),"</a></td>\n";
			print "<td>",$u->get_value('uidNumber'),"</td>\n";
			print "<td>",$u->get_value('cn') || "<br>",
			      "</td>\n";
			print "<td>",$u->get_value('homeDirectory') || "<br>",
			      "</td>\n";
			print "<td>",$u->get_value('loginShell') || "<br>",
			      "</td>\n";
			print "<td>",$classes{$samba_class} ? $text{'yes'}
						    : $text{'no'},"</td>\n";
			print "<td>",$classes{$cyrus_class} ? $text{'yes'}
						    : $text{'no'},"</td>\n";
			print "</tr>\n";
			}
		print "</table>\n";
		}
	&ui_print_footer("", $text{'index_return'});
	}


