# This script converts replaces saved by replace.pl to a triggers-file that can be used by trigger.pl
# This is not an irssi script. You should use this from the command line.
# Usage:
#  perl convert-replace-trigger.pl [irssi-dir]
# if no directory is specified, it will asume you use the default ~/.irssi
#
# http://wouter.coekaerts.be/irssi/

use strict;
use warnings;
use IO::File;
use Data::Dumper;

print "convert-replace-trigger 1.1\n";

my (@replaces, @triggers, $irssidir);

if (!$ARGV[0]) {
	$irssidir = $ENV{'HOME'};
	print "no arguments given, assuming your irssi directory is $irssidir\n";
} else {
	$irssidir = $ARGV[0];
	print "using $irssidir as irssi directory\n";
}

$irssidir =~ s/\/$//; # strip last /
print "reading replaces from $irssidir/replaces...\n";
my $io = new IO::File "$irssidir/replaces", "r";
if (not defined $io) {
	print "error opening replaces file, aborting\n";
	exit;
}
if (defined $io) {
	no strict 'vars';
	my $text;
	$text .= $_ foreach ($io->getlines);
	my $rep = eval "$text";
	@replaces = @$rep if ref $rep;
	$io->close();
}
print(@replaces . " replaces loaded\n");

if (-e "$irssidir/triggers") { # there already is a triggers file
	print "reading existing triggers from $irssidir/triggers...\n";
	$io = new IO::File "$irssidir/triggers", "r";
	if (not defined $io) {
		print "triggers file already exists, but I can't open it. please remove it.\n";
		exit;
	}
	no strict 'vars';
	my $text;
	$text .= $_ foreach ($io->getlines);
	my $rep = eval "$text";
	@triggers = @$rep if ref $rep;
	$io->close();
}

if (@triggers) {
	print (@triggers . " triggers already exist in the triggers file, keeping them\n");
}

print "converting...\n";
REPLACE:
foreach my $replace (@replaces) {
	if ($replace->{'case'}) {
		delete $replace->{'case'};
	} else {
		$replace->{'modifiers'} = 'i';
	}

	if ($replace->{'command'}) {
		$replace->{'command'} = $replace->{'replacement'};
	} else {
		$replace->{'replace'} = $replace->{'replacement'};
	}
	delete $replace->{'replacement'};

	my $isduplicate = 1;
	foreach my $trigger (@triggers) {
		if (scalar(keys(%$trigger)) == scalar(keys(%$replace))) {
			foreach my $key (keys(%$trigger)) {
				if (!(defined($trigger->{$key}) && $replace->{$key} eq $trigger->{$key})) {
					$isduplicate = 0;
				}
			}
		} else {
			$isduplicate = 0;
		}
	}

	if ($isduplicate) {
		print "skipping duplicate trigger\n";
		next REPLACE;
	}
	
	push @triggers, $replace;
}

print "saving triggers...\n";
$io = new IO::File "$irssidir/triggers", "w";
if (!defined $io) {
	print "Error writing triggers\n";
	exit;
}
my $dumper = Data::Dumper->new([\@triggers]);
$dumper->Purity(1)->Deepcopy(1);
$io->print($dumper->Dump);
$io->close;
print("Done. replaces successfully converted to triggers.\n");
