#!/usr/bin/perl

if (!@ARGV)
  {
    &printHelp;
    exit(1);
  }

#---- addAttribute -----------------------------------------------------------#

sub addAttribute($)
  {
    my ($attribute) = @_;

    if (exists $VALUE{$attribute})
      {
	if($username eq '')
	  {
	    $username = $VALUE{$attribute};
	  }
	else
	  {
	    $username .= ".$VALUE{$attribute}";
	  }
      }
  }

#---- subject2user -----------------------------------------------------------#

sub subject2user
  {
    my ($subject) = @_;
    my $field;
    %VALUE = ();

    my @Fields = split(/\/([^\/]*)/, $subject);

    foreach $field (@Fields)
      {
	if ($field =~ /^(.+)=(.+)/)
	  {	
	    my $attribute = $1;
	    my $value     = $2;

	    # CN management
            if ($attribute eq 'CN')
	      {
		@Names = split(/ /, $value);
		$value = @Names[0];
		for ($i = 1; $i <= $#Names; $i++)
		  {
		    $value .= substr(@Names[$i], 0, 1);
		  }	
	      }

	    $value =~ s/\s+/./g;
	    $value =~ s/@+/./g;

	    if (! exists $VALUE{$attribute})
	      {
		$VALUE{$attribute} = $value;
	      }
	    else
	      {
		$VALUE{$attribute} .= ".$value";
	      }
	  }
      }

    $username = '';

    addAttribute('CN');
#   addAttribute('Email')
#   addAttribute('L');
#   addAttribute('O');
#   addAttribute('C');

    $username = lc($username);

    if($username)
      {
	print "$username\n";
      }
    else
      {
	die "$0: unable to extract a valid username\n\n";
      }
  }

#---- printHelp --------------------------------------------------------------#

sub printHelp
  {
    print "subject2user <subject>\n";
  }

#=============================================================================#

subject2user($ARGV[0]);

#=============================================================================#
