package Xchat::VPIT::Services;

use strict;
use warnings;

use Xchat qw/:all/;

use lib get_info 'xchatdir';
use Xchat::XPI;

our $VERSION = '0.03';

my $ph;

sub get_servers_ctxt {
 my %s;
 return map $_->{context},
         grep !$s{$_->{server}}++,
          sort { $a->{type} <=> $b->{type} }
           get_list 'channels';
}

hook_command 'ID', sub {
 return EAT_PLUGIN if $_[0][1];
 my $passwd = get_info 'nickserv';
 return EAT_ALL unless $passwd;
 command 'ID ' . $passwd;
 return EAT_ALL;
}, {
 help_text => 'ID [password], identify you to NickServ'
};

hook_command 'AID', sub {
 my $forcepasswd = $_[0][1];
 my $oldctxt = get_context;
 my @contexts = get_servers_ctxt;
 for (@contexts) {
  set_context $_;
  my $passwd = $forcepasswd || get_info 'nickserv';
  next unless $passwd;
  command 'ID ' . $passwd;
 }
 set_context $oldctxt;
 return EAT_ALL;
}, {
 help_text => 'AID [password], identify you on all servers'
};

hook_command 'GHOST', sub {
 return EAT_PLUGIN if $_[0][2];
 my $target = $_[0][1] || get_prefs 'irc_nick1';
 my $passwd = get_info 'nickserv';
 return EAT_ALL unless $target && $passwd;
 if (nickcmp(get_info('nick'), $target)) {
  command join ' ', 'GHOST', $target, $passwd;
 }
 return EAT_ALL;
}, {
 help_text => 'GHOST [nick] [password], kill the client currently connected with your nickname'
};

hook_command 'AGHOST', sub {
 my $target = $_[0][1] || get_prefs 'irc_nick1';
 return EAT_ALL unless $target;
 my $forcepasswd = $_[0][2];
 my $oldctxt = get_context;
 my @contexts = get_servers_ctxt;
 for (@contexts) {
  set_context $_;
  my $passwd = $forcepasswd || get_info 'nickserv';
  next unless $passwd;
  if (nickcmp(get_info('nick'), $target)) {
   command join ' ', 'GHOST', $target, $passwd;
  }
 }
 set_context $oldctxt;
 return EAT_ALL;
}, {
 help_text => 'AGHOST [nick] [password], kill usurping clients on all servers'
};

sub csmode {
 my $cmd = join ' ', 'QUOTE CHANSERV', $_[2], get_info('channel');
 my @targets = @{$_[0]};
 shift @targets;
 @targets = (get_info 'nick') unless @targets;
 command join ' ', $cmd, $_ for @targets;
 return EAT_ALL;
}

hook_command "C$_", \&csmode, {
 data => $_,
 help_text => join ' ', $_, '[nicks] ,', (lc $_),
    'the specified targets (or you if none) on the current channel via ChanServ'
} for map { $_, "DE$_" } qw/VOICE HALFOP OP PROTECT/;

$ph = Xchat::XPI->new(
 name   => 'IRC Services',
 tag    => 'Services',
 desc   => 'Various IRC services helpers',
 author => 'Vincent Pit (VPIT)',
 email  => 'perl@profvince.com',
 url    => 'http://www.profvince.com',
);

1;
