#!/usr/bin/perl -w

BEGIN {
    # Set default current working directory
    if( $ENV{"SCRIPT_FILENAME"} && $ENV{"SCRIPT_FILENAME"} =~ /^(.+)\/[^\/]+$/ ) {
        chdir $1;
    }
    # Set library paths in @INC at compile time
    unshift @INC, '.';
    require 'setlib.cfg';
}

use TWiki;

use CGI::Carp qw(fatalsToBrowser);
use CGI;

my $query = new CGI;

my $thePathInfo = $query->path_info(); 
my $theRemoteUser = $query->remote_user();
my $theUrl = $query->url;
my $theTopic = $query->param( 'topic' ) || "";

my( $topic, $webName, $dummy, $userName ) = 
  TWiki::initialize( $thePathInfo, $theRemoteUser, $theTopic,
                     $theUrl, $query );
$dummy = "";  # to suppress warning

print "| \$user | OLDuserToWikiName(\$user) | NEWuserToWikiName(\$user) | \n";

my @userNameList = ('guest', 'someguy', 'someGuy', 'SomeGuy', 'ntdomain/username', 'McCinnon', 'Main.UserName', 'Strange/Web.NameOfTopic');

foreach $user (@userNameList) {
    print "| $user | ".OLDuserToWikiName($user)." | ".NEWuserToWikiName($user)." | \n";
}

=pod

---++ OLDuserToWikiName( $loginUser, $dontAddWeb )
Return value: $wikiName

Translates intranet username (e.g. jsmith) to WikiName (e.g. JaneSmith)
userToWikiListInit must be called before this function is used.

Unless $dontAddWeb is set, "Main." is prepended to the returned WikiName.

=cut

sub OLDuserToWikiName
{
    my( $loginUser, $dontAddWeb ) = @_;
    
    if( !$loginUser ) {
        return "";
    }

    $loginUser =~ s/$TWiki::securityFilter//go;
    my $wUser = $TWiki::userToWikiList{ $loginUser } || $loginUser;
    if( $dontAddWeb ) {
        return $wUser;
    }
    return "$TWiki::mainWebname.$wUser";
}


=pod

---++ NEWuserToWikiName( $loginUser, $dontAddWeb )
Return value: $wikiName

Translates intranet username (e.g. jsmith) to WikiName (e.g. JaneSmith)
userToWikiListInit must be called before this function is used.

Unless $dontAddWeb is set, "Main." is prepended to the returned WikiName.

if you give an invalid username, we just return that (no appending Main. blindy)

SMELL: the userToWikiList cache should really contain the WebName so its possible 
		to have userTopics in more than just the MainWeb (what if you move a user topic?)

=cut

sub NEWuserToWikiName
{
    my( $loginUser, $dontAddWeb ) = @_;
    
    if( !$loginUser ) {
        return "";
    }

    $loginUser =~ s/$TWiki::securityFilter//go;
    my $wUser = $TWiki::userToWikiList{ $loginUser };
    if ( ! $wUser ) { #if we didn't find a user, just use the input param (NoPasswdUser, or de-registered)
		$wUser = $loginUser;
	}

    if( ! $dontAddWeb ) {
		my $web = $TWiki::mainWebname;
		( $web, $wUser ) = TWiki::Store::normalizeWebTopicName( $web, $wUser );

		if ( TWiki::isWikiName($wUser) ) {
            $wUser = "$web.$wUser";
		}
    }
   
   return $wUser;
}

