use Digest::SHA1  qw(sha1_hex);
use strict;
use vars qw($VERSION %IRSSI);

use Irssi;

$VERSION = '0.1';
%IRSSI = (
    authors     => 'Andreas Ehliar',
    contact     => 'ehliar@lysator.liu.se',
    name        => 'Password preventer',
    description => 'This script prevents you from accidentally disclosing secret phrases',
    license     => 'GPL',
);

# Prevent passwords from leaking to IRC by mistake
#
# It is easy to accidentally change the focus of your window manager
# to the IRC terminal instead of your webbrowser. Or you might have
# several machines and accidentally type your password on the wrong
# keyboard.
#
# This script is designed to lessen the chance of valuable passwords
# leaking to your favourite IRC channel by mistake.

# TODO:
#  * Do not save hashes in the script itself.
#  * Create some way to override the protection.
#    This could be used to protect your Nickserv password for example.

sub mycommand {
    my ($server, $data, $nick, $address) = @_;
    my ($line, $server,$item) = @_;

    my $digest;
    my $stringlen = length($line);


    # You will have to generate the hashes of the 
    # words/phrases you want to protect in some way.
    # A simple way is to use the sha1sum command.
    # (However, remember to clean up your shell history
    #  files afterwards.)

    # ehliar@adriana:~>echo -n topsecretphrase |sha1sum 
    # 76301422b7113e66e51caa96fe1f23854ad2fd69  -
    # ehliar@adriana:~>echo -n myothersecret |sha1sum                
    # faf86147f6e36717616450c2a75e6e302c59ea73  -

    # Insert the SHA1 hashes of the words you want to protect here
    my @digests = ("76301422b7113e66e51caa96fe1f23854ad2fd69",
		   "faf86147f6e36717616450c2a75e6e302c59ea73");

    foreach $digest (@digests) {
	# Change $sumlen to less than 3 if you for some reason
	# have valuable passwords shorter than 3 characters.
	for(my $sumlen = 3;$sumlen <= $stringlen ;$sumlen++)
	{
	    for(my $start = 0;$start <= $stringlen - $sumlen;$start++)
	    {
		if($digest eq sha1_hex(substr($line,$start,$sumlen))){
		    # The substring of $line matches the hashed value,
		    # Warn the user and abort the line
		    print "Warning: You really don't want to send that line...";
		    Irssi::signal_stop();
		    return;
		}
	    }
	}
    }

}

Irssi::signal_add("send command","mycommand") ;

