#!/usr/bin/perl -w
use strict;
use Text::Tabs;

my $VERSION = '0.3';

my $licq	= @ARGV ? shift @ARGV : "$ENV{HOME}/.licq";
my $dir		= "$licq/users";
my $pid		= "$licq/licq.pid";

my ($file, %hash, $uin, $alias, $i);

$| = 1;

print "Licq Contact List Orderer v$VERSION\n",
      "Coded by Stas <stas\@grad.icmc.sc.usp.br>\n\n",
      
      "Usage: $0 [/home/user/.licq]\n",
      "(if no parameter was specified, \"~/.licq\" will be used)\n",
      "NOTE: this program *only* changes .licq/users.conf and keeps old\n",
      "      file at .licq/users.bak\n\n\n";

if (-e $pid) {
   open (PID, $pid) || "can't open $pid: $!\n";
   warn " !!! WARNING !!!  Check if Licq is running on PID ", scalar <PID>,
        "(if so, turn it off and try again; if it's not, remove $pid)\n";
   close PID;
   
   exit -1;
}

print " * Ordering your contact list at $dir:\n";

opendir (USERS, $dir) || die "can't open licq users dir: $!\n";
foreach $uin (readdir USERS) {
   $file = "$dir/$uin";
   next if not ($uin =~ s/\.uin$//) or not -f $file;
   open (USER, $file) || die "can't open $file :$!\n";
   while (<USER>) {
      chomp;
      ($alias) = /^Alias = (.*)$/i;
      last if defined $alias;
   }
   $hash {$uin} = (defined $alias) ? $alias : $uin;
   close USER;
}
closedir USERS;

rename ("$dir.conf", "$dir.bak") || die "can't backup users.conf: $!\n";

open (CONF, ">$dir.conf") || die "can't write to users.conf: $!\n";
print CONF "[users]\n",
           "NumOfUsers = ", scalar keys %hash, "\n";
foreach $uin (
sort {
   (lc $hash {$b} cmp lc $hash {$a}) or ($b <=> $a)
} keys %hash) {
   print '.';
   print CONF unexpand (sprintf "User%d = %-14s\t# %s\n", ++$i, $uin, $hash {$uin});
}
close CONF;

print "\n * Done! $i users ordered!\n";
exit;
