#!/usr/bin/env perl

# QIP 2 SIM history converter
# (c) 2007 Mike Kuznetsov, mike@molinos.ru. License: GPLv2

# Configure:
my $qipdir = '/path/to/Qip/History';
my $simdir = '/path/to/Sim/History';
my $youricq = '00000001';
#

my $coricq;
my $inout;
my $message;
my $ts;
my $first;
my $line;
my @m_date;
my $simfile;
my $qipfile;

use Time::Local 'timelocal';
use Text::Iconv;

$converter = Text::Iconv->new("cp1251", "utf-8");

sub print_message {
    chomp($message);
    $message =~ s/(.*)\\n$/$1/g;
    print SIMFILE "[Message]\n";
    print SIMFILE "Text=\"$message\"\n";
    print SIMFILE "Flags=1\n" if ($inout =~ "in");
    print SIMFILE "Background=16777215\n";
    print SIMFILE "Foreground=0\n";
    print SIMFILE "Time=$ts\n";
    $message = "";
}

sub append_line {
    $line =~ s/\\/\\\\/g;
    $line =~ s/\"/\\x22/g;
    $message = $message . $line . '\n';
}

sub date_conv {
    $line =~ s/.*\(([^)]+)\)$/$1/g;
    $line =~ s/[:\ \/]/\:/g;
    @m_date = split (/:/, $line);
    $ts=timelocal($m_date[2],$m_date[1],$m_date[0],$m_date[3],$m_date[4]-1,$m_date[5]);
}

opendir DIR, $qipdir or die "Can't open QIP history directory\n";

while($qipfile = readdir DIR) {
    $first = 'yes';
    if ($qipfile =~ "^[0-9]") {
        open(QIPFILE, "$qipdir/$qipfile");
        $coricq = $qipfile;
        $coricq =~ s/(.*)\.txt$/$1/g;
        $simfile = "ICQ.$youricq.$coricq";
        open(SIMFILE, ">>$simdir/$simfile") or die "Can't open SIM history directory\n";
        while ($line = <QIPFILE>) {
            $line =~ s/\r//g;
            $line = $converter->convert($line);
            chomp($line);
            next unless ($line);
            if ($line =~ "--------------------------------------<-") {
                print_message if (!$first);
                $inout = "ints";
                $first = "";
            } elsif ($line =~ "-------------------------------------->-") {
                print_message if (!$first);
                $inout = "outts";
                $first = "";
            } elsif ($inout =~ "ints") {
                date_conv;
                $inout = "in";
            } elsif ($inout =~ "outts") {
                date_conv;
                $inout = "out";
            } elsif ($inout =~ "in") {
                append_line;
            } elsif ($inout =~ "out") {
                append_line;
            } else {
                die "ERROR!\n";
            }
        }
    print_message;
    close(SIMFILE);
    close(QIPFILE);
    }
}
closedir DIR;

