###########################################################################
##
## HEX for irssi 
## Like IDEA plugin but uses HEX :-)
##
## RootBear / OH3NWQ Dec 2010
##
## See the color formats near the end of the script
##
## Based on MORSE for irssi by
## Goblet / OH2MMY  Nov 2001
##
## Might not support WTF8, but who the fuck cares.
##
## This script is published under EVVKTVH: http://evvk.com/evvktvh.html
## Insert your bug reports and/or complaints into your rectum.
##
###########################################################################

use Irssi;
use Irssi::Irc;
use Irssi::UI;
use strict;

my $version = "1.0";

sub encode_hex_ ($)
{
    my $str = shift;
    my $ret = unpack 'H*', $str;
    return $ret;
}


sub decode_hex_ ($)
{
    my $str = shift;
    my $original = $str;
    if (length($str) % 2) {
        return "error: ".$original;
    }
    $str =~ s/[^A-Fa-f0-9]//g;
    if (length($str) % 2) {
        return "error: ".$original;
    }
    return "" unless length $str;
    my $binary_string = pack 'H*', $str; 
    return $binary_string;	
}


sub encode_hex {
  my ($str) = @_;
  $str = encode_hex_($str);
  return $str;
}

sub decode_hex {
  my ($str) = @_;
  $str = decode_hex_($str);
  return $str;
}


sub cmd_hex_say {
  my ($data,$server,$witem) = @_;
  my $window = Irssi::active_win();
  my $encoded;

  if (!$server || !$server->{connected}) {
      Irssi::print("Not connected to server");
      return;
  }
  if ($data && $witem->{type} eq "CHANNEL") {
      $encoded = encode_hex($data);

      $witem->command("^MSG ".$witem->{name}.
                     " |*E*|HEX|$version|$encoded|");
  } else {
      Irssi::print("No active channel in window");
  }
  $window->printformat(MSGLEVEL_MSGS,'hex_own',$data);
}

sub check_hex {
  my ($srv, $data, $nick, $addr) = @_;
  my ($dest, $text) = split(/ :/, $data, 2);
  my $server = Irssi::active_server();
  my ($dummy, $tag, $proto, $ver, $target) = split(/\|/,$text);
  if ($tag eq "*E*" && $proto eq "HEX") {
    $server->printformat($dest,MSGLEVEL_PUBLIC,'hex_pub',
                         $nick,decode_hex($target));
    Irssi::signal_stop();
  }
}

# Here you can change the color formats
Irssi::theme_register([
  'hex_own', '%yHEX %n%w>%g $0-',
  'hex_pub', '%yHEX %n%c<$0>%n $1-'
]);   

Irssi::signal_add("event privmsg", "check_hex");
Irssi::command_bind("hex", "cmd_hex_say");
Irssi::print("HEX $version loaded :-P");

