#!/usr/bin/perl

use XML::Writer;

$privileged=3;
$onlineNotify=2;
$comments=1;
$username=0;
$writer=0;

print "This small script will transform your old nicotine config file to the museek standard,
you can get further assistance from:
\t - museek forum on soulseek
\t - http://mozart.dnsalias.net/museek.hmtl
\t - rhwinter@gmail.com
***Please notice that***:
-there is still no conversion for (means you'll have to do it MANUALLY):
\t -privileged
\t -alerts (online notify)
\t -the user image
\t -the ongoing downloads (though this can help you to do that:http://mozart.dnsalias.net/museek/)
\t -shared folders
-you have to review the generated file (which means this script is not failproff!!)
-you'll have to rename the 'NEWconfig.xml' file to 'config.xml' and put it into '~/.museek'\n\n";

%allValues = getAllValuesFromFile();
@userList     = parseBuddieList("userlist");
@banList      = parseSimpleList("banlist");
@autoJoinList = parseSimpleList("autojoin");
@ignoreList   = parseSimpleList("ignorelist");

writeXML();

print "\nScript finished! - Thanks for using it!\n";
######################

sub getAllValuesFromFile(){
    my @values, %toReturn;
    # open the file
    chop(my $curUser=`whoami`);
    print"Parsing '/home/$curUser/nicotine/config' file...";
    open (CONFILE, "/home/$curUser/.nicotine/config");
    # for testing: open (CONFILE, "config");
    # parse it
    while (<CONFILE>){
	chomp;
         # separate each line by the ' = ' sign
	@values=split(/ = /,$_);
	# put it in a hash table
	$toReturn{$values[0]}=$values[1];
    }
    # close the file
    close(CONFILE);
    # return the hash table
    print" done.\n\n";
    return %toReturn;
}

# this will transform a list like [['one,'two','three'],['oneb',twob','threeb']] into an array of arrays
sub parseBuddieList(){
    my @eachInfo, $trash, @allUsers=(), $listName=0, $theList=0;
    $listName=$_[0];
    $theList=$allValues{$listName};
    ($trash,$theList)=split(/\[\[/,$theList);
    ($theList,$trash)=split(/\]\]/,$theList);
    @eachInfo = split(/\], \[/,$theList);
    foreach $info (@eachInfo){
	# redeclare last user
	 my @lastuser;
	if($info =~ /[\'|\"](.*)[\'|\"]\, [\'|\"](.*)[\'|\"]\, (\w*)\, (\w*)/){
	    @lastuser=($1, $2, $3, $4);
	    push(@allUsers, \@lastuser);
	}else{
	    print "ERROR: this does not match the user regex $info";
	}
	# print "username:$lastuser[$username] comments:$lastuser[$comments] online:$lastuser[$onlineNotify] priv:$lastuser[$privileged]\n";
    }
    # we return the list of users
    return @allUsers;
}
# this will transform a list like ['blabla', 'alksal', 'popo'] into an array (uses the *allValues* hash table)
sub parseSimpleList(){
    my @localAllValues=(), $trash=0, @finalValues=(), $listName=0, $theList=0;
    print @finalValues;
    $listName=$_[0];
    $theList=$allValues{$listName}; # get the 'allValues' at the specified location!!!
    ($trash,$theList)=split(/\[/,$theList);
    ($theList,$trash)=split(/\]/,$theList);
    @localAllValues = split(/\, /,$theList);
    foreach my $value (@localAllValues){
	$value =~ s/[\'|\"](.*)[\'|\"]/$1/g;
	push(@finalValues,$value);
	# print "$listName:$value\n";
    }
    return @finalValues;
}

sub writeXML(){
    # initialize the XML file
    use IO::File;
    my $output = new IO::File(">NEWconfig.xml");
    $writer = new XML::Writer(OUTPUT => $output, DATA_MODE => 'true', DATA_INDENT => 2);
    $writer->xmlDecl;
    
    ######################################
     # make a hash table to ease the job:
     %allMultipleEmptyTags=(
    	'autojoin'=>\@autoJoinList,
    	'banned'=>\@banList,
	'ignored'=>\@ignoreList
     );
    
    # then multiple empty tags
    $writer ->startTag('museekd');
    foreach $key (keys %allMultipleEmptyTags) {
	@value = @{$allMultipleEmptyTags{$key}};
	$writer->startTag('domain', 'id' =>$key);
	putSimpleValuesOnXML(@value);	   
	$writer->endTag('domain');    
    }
    
    ######################################
    # now non empty ones

    @host=("host","server.slsknet.org");
    @pass=("password",$allValues{"passw"});
    @port=("port",2240);
    @username=("username",$allValues{"login"});
    @server=(\@host, \@pass, \@port, \@username);

    @dDir=("download-dir",$allValues{"downloaddir"});
    @iDir=("incomplete-dir",$allValues{"incompletedir"});
    @uploadSlots=("upload_slots",$allValues{"uploadslots"});
    @upFriendsPolicy=("privilege_buddies",$allValues{"friendsnolimits"});
    @friendsOnly=("only_buddies",$allValues{"friendsonly"});
    # static for now! <key id="downloads">$(CONFIG).downloads</key>
    @downloads = ("downloads", "\$(CONFIG).downloads");
    @transfers=(\@dDir,\@iDir,\@uploadSlots,\@upFriendsPolicy, \@friendsOnly, \@downloads);

    @descr=("text",$allValues{"descr"});
    # static for now!
    @image=("image","\$(CONFIG).image");
    @userInfo=(\@descr, \@image);
   
    # get the interface password
    print "Please enter a password for the interface (will apear on the screen as you type):";
    $interfacePass= <STDIN>;
    chomp($interfacePass);
    @iPass=("password",$interfacePass);
    @interfaces=(\@iPass);
    
    %allFilledTags=(
	'buddies'=>\@userList,
	'server'=>\@server,
	'transfers'=>\@transfers,
	'userinfo'=>\@userInfo,
	'interfaces'=>\@interfaces
    );
    
    foreach $key (keys %allFilledTags) {
	@value = @{$allFilledTags{$key}};
	$writer->startTag('domain', 'id' =>$key);
	putComplexValuesOnXML(@value);
	$writer->endTag('domain');
    }
    
    #####################
    # print missing static values
    printEverythingElse();
    
    ############
    # end it all
    print"Going to write 'NEWconfig.xml' file...";
    $writer->endTag('museekd');
    $writer->end();
    $output->close();
    print" done.\n";
}

# will add tags from the $_ array
sub putSimpleValuesOnXML(){
    @arrayOfValues=@_;
    foreach $i (@arrayOfValues){    
	$writer->emptyTag('key','id' =>$i);
    }
}

sub putComplexValuesOnXML(){
    # variable sent has to be an array of references to arrays!!
    @arrayOfValues=@_;
    foreach $i (@arrayOfValues){
	$writer->startTag('key','id' =>@$i[0]);
	$writer->characters(@$i[1]);
	$writer->endTag('key');
	
    }
}

sub printEverythingElse(){
    $writer->startTag('domain', 'id'=>"clients");
    $writer->startTag('key', id=>"connectmode");
    $writer->characters("active");
    $writer->endTag('key');
    $writer->endTag('domain');
    
    $writer->startTag('domain', 'id'=>"clients.bind");
    $writer->startTag('key', id=>"first");
    $writer->characters("2234");
    $writer->endTag('key');
    $writer->startTag('key', id=>"last");
    $writer->characters("2240");
    $writer->endTag('key');
    $writer->endTag('domain');
    
    $writer->startTag('domain', 'id'=>"encoding");
    $writer->startTag('key', id=>"filesystem");
    $writer->characters("latin1");
    $writer->endTag('key');
    $writer->startTag('key', id=>"network");
    $writer->characters("utf-8");
    $writer->endTag('key');
    $writer->endTag('domain');
    
    $writer->startTag('domain', 'id'=>"encoding.rooms");
    $writer->endTag('domain');
    
    $writer->startTag('domain', 'id'=>"encoding.users");
    $writer->endTag('domain');
    
    $writer->startTag('domain', 'id'=>"interfaces.bind");
    $writer->emptyTag('key', id=>"/tmp/museekd.\$(USER)");
    $writer->emptyTag('key', id=>"localhost:2240");
    $writer->endTag('domain');
    
    # this we would have to get from files such as conf config.files.db (?)...
    $writer->startTag('domain', 'id'=>"shares");
    $writer->startTag('key', id=>"database");
    $writer->characters("\$(CONFIG).shares");
    $writer->endTag('key');
    $writer->endTag('domain');
};

__END__


