package APKPM::LDAP;

use base qw(Gearman::Driver::Worker);
use Moose;
use Time::HiRes;
use Data::Dump qw(dump);
use Regexp::Common qw(net);

with 'APKPM::Config';
with 'APKPM::Gearman';

use Net::LDAP;
use Redis;

sub prefix { 'LDAP_' }

sub process_name {
	my ( $self, $orig, $job_name ) = @_;
	warn "# process_name $orig $job_name\n";
	return "$orig ($job_name)";
}

sub search : Job : Encode(e_json) : MinProcesses(0) {
	my ( $self, $job, $workload ) = @_;

	my $filter =
		$workload =~ m/$RE{net}{IPv4}/ ? "dhcpStatements=fixed-address $workload" :
		$workload =~ m/\w+=/ ? $workload : # have filter specified
		"cn=*$workload*" ; # defailt: search for user
	;
	warn "# search ",dump($filter);

	my $ldap = Net::LDAP->new($self->config('ldaphost')) or die $@;
	my $mesg = $ldap->bind($self->config('ldapusername'),Password => $self->config('ldappasswd'));
#	$mesg = $ldap->search(base => $self->config('ldapbase'), filter => $filter);
	$mesg = $ldap->search(base => 'cn=clientnetVoD,cn=Dhcp,ou=Servers,dc=portus,dc=isp' , filter => $filter);
	warn "# found ", $mesg->count, " entries";
	my $entries = [];

	my $redis = Redis->new;

	for ( my $i = 0; $i < $mesg->count; $i++ ) {
		my $entry = $mesg->entry($i);
		my $e = { dn => $entry->dn };
		foreach my $attr ( $entry->attributes ) {
			$e->{$attr} = join("\n", $entry->get_value($attr));
			if ( $attr =~ m/dhcpOption/ ) {
				my $vendor = (
					grep { /vendor-class-identifier/ }
					$entry->get_value($attr)
				)[0];
				$vendor =~ s/^\S+\s+\"([^"]+)\"/$1/;
				$e->{_cpe_vendor} = $vendor;
				$e->{_cpe_parser} =
					$vendor =~ m/SAMSUNG/ ? 'Davolink' :
					$vendor =~ m/zte/     ? 'EasyGateway' :
					undef;
			}
		}
		push @$entries, $e;

		my $key = 'LDAP.' . $e->{cn};
		$redis->set( $key => $self->e_json($e) );
		$redis->expire( $key => 15 * 60 );

	}
#	warn "## entries = ",dump $entries;
	return $entries;
}

1;
