#!/usr/bin/perl -w

use strict;
use CGI;
use Net::LDAP;

my $ldapserver = "";
my $base = "";

my $cgi = CGI->new();

print $cgi->header();

my $search = $cgi->param('search');

my $ldap = Net::LDAP->new($ldapserver) || die("Failed to connect to LDAP server: $@");

my $mesg = $ldap->bind(version => 3);

my @Attrs = ( );

my $result = $ldap->search ( base => $base,
			     scope   => "sub",
			     filter  => "cn=*$search*",
			     attrs   => @Attrs );

my $href = $result->as_struct;

#print Dumper $href;

my $key;

print "<CiscoIPPhoneDirectory>\n";
print "\t<Title>Home Directory</Title>\n";
print "\t<Prompt>Who you gonna call?</Prompt>\n";

foreach $key (keys %{$href}) {
  my $givenname = $href->{$key}->{givenname}->[0];
  my $sn = $href->{$key}->{sn}->[0];
  foreach (@{$href->{$key}->{homephone}}) {
    my $phone = phone_convert($_);
    print "\t<DirectoryEntry>\n";
    print "\t\t<Name>$sn, $givenname</Name>\n";
    print "\t\t<Telephone>$phone</Telephone>\n";
    print "\t</DirectoryEntry>\n";
  }
  foreach (@{$href->{$key}->{mobile}}) {
    my $phone = phone_convert($_);
    print "\t<DirectoryEntry>\n";
    print "\t\t<Name>$sn, $givenname</Name>\n";
    print "\t\t<Telephone>$phone</Telephone>\n";
    print "\t</DirectoryEntry>\n";
  }
  foreach (@{$href->{$key}->{telephone}}) {
    my $phone = phone_convert($_);
    print "\t<DirectoryEntry>\n";
    print "\t\t<Name>$sn, $givenname</Name>\n";
    print "\t\t<Telephone>$phone</Telephone>\n";
    print "\t</DirectoryEntry>\n";
  }
}

print "</CiscoIPPhoneDirectory>\n";

sub phone_convert {
  my $phone = shift;
  $phone=~s/^\+44/90/;
  $phone=~s/^\+/900/;

  return $phone;
}
