use strict;
use warnings;
use vars qw($VERSION %IRSSI);
use Irssi;

$VERSION = '0.0.1';
%IRSSI = (
	name => 'uppush',
	authors => 'Bapt',
	contact => 'bapt@FreeBSD.org',
	description => 'exec shell on push',
	license => 'MIT',
);
# To use:
# $ cp uppush.pl ~/.irssi/scripts/uppush.pl
# irssi> /load perl
# irssi> /script load uppush
# irssi> /set uppush_ignore_hilight 0 		    # ignore hilights of priority 0
# irssi> /set uppush_own on           		    # turn on own notifications
# irssi> /set uppush_channel https://url            # channel url

my %config;

Irssi::settings_add_int('uppush', 'uppush_ignore_hilight' => -1);
$config{'ignore_hilight'} = Irssi::settings_get_int('uppush_ignore_hilight');

Irssi::settings_add_bool('uppush', 'uppush_own', 0);
$config{'own'} = Irssi::settings_get_bool('uppush_own');

Irssi::settings_add_str('uppush', 'uppush_channel', "");
$config{'channel'} = Irssi::settings_get_str('uppush_channel');

Irssi::signal_add(
    'setup changed' => sub {
        $config{'ignore_hilight'} = Irssi::settings_get_int('uppush_ignore_hilight');
        $config{'own'} = Irssi::settings_get_bool('uppush_own');
	$config{'channel'} = Irssi::settings_get_str('uppush_channel');
    }
);

#	private messages
sub priv_msg {
	my ($server, $msg, $nick, $address, $target) = @_;
	my $msg_stripped = Irssi::strip_codes($msg);
	my $network = $server->{tag};
	sendmsg('' . $network . ' ' . $nick . ' ' . $msg_stripped);
}

#	hilight's
sub hilight {
	my ($dest, $text, $stripped) = @_;
    my $ihl = $config{'ignore_hilight'};
	if ($dest->{level} & MSGLEVEL_HILIGHT && $dest->{hilight_priority} != $ihl) {
		my $server = $dest->{server};
		my $network = $server->{tag};
		sendmsg($network . ' ' . $dest->{target} . ' ' . $stripped);
	}
}

#	own messages
sub own_public {
	my ($dest, $msg, $target) = @_;
	if ($config{'own'}) {
		sendmsg($dest->{'nick'} . ' ' .$msg );
	}
}

sub own_private {
	my ($dest, $msg, $target, $orig_target) = @_;
	if ($config{'own'}) {
		sendmsg($dest->{'nick'} . ' ' .$msg );
	}
}

#	write to file
sub sendmsg {
	my ($text) = @_;
	my $fnfile = Irssi::get_irssi_dir() . "/uppush";
	system "/usr/local/bin/curl -so /dev/null  -d \"" . $text . "\" ". $config{'channel'};
}

Irssi::signal_add_last("message private", "priv_msg");
Irssi::signal_add_last("print text", "hilight");
Irssi::signal_add_last("message own_public", "own_public");
Irssi::signal_add_last("message own_private", "own_private");
