#!/usr/bin/perl
# GPLv3 or later
# (C) 2016 Svetlana Tkachenko svetlana@members.fsf.org

use strict;
use warnings;

BEGIN {
    unless (exists $::{"Irssi::"}) {
	require Pod::Usage;
	Pod::Usage::pod2usage(-verbose => 2);
    }
}

use Irssi;
our $VERSION = '0.05';
our %IRSSI = (
    authors => 'svetlana',
    name => 'nu',
    description => 'ops someone random and deops me when it can',
    license => 'GPL',
    );

sub message_mode {
    # set config vars
    my $place = '#<XXX FIXME>';
    # get data
    my ($server_rec, $channel_text, $sender_text, $address_text, $data_text) = @_;
    # output debug info
    Irssi::print("chan: $channel_text, sender: $sender_text, $address_text, $data_text");
    # if wrong channel, then bail out
    if($channel_text ne $place) {return;}
    # figure out what my nick is
    my $mynick =  $server_rec->{nick};
    # check if the mode change relates to me in any way
    if($data_text =~ $mynick){
	Irssi::print("...I ($mynick) was involved in a mode change");
	# check if I am an op now
	my $mychan = $server_rec->channel_find($place);
	my $am_op = $mychan->nick_find($mynick)->{op};
	Irssi::print("...am I an op? $am_op");
	# get the list of random people who are in the nick list and are not yet opped
	my @nonops = (); # stolen from https://raw.githubusercontent.com/irssi/scripts.irssi.org/gh-pages/scripts/chops.pl
	foreach my $nick ($mychan->nicks()) {
	    push(@nonops, $nick) if (!$nick->{op} and !($nick eq $mynick));
	}

	# op someone (not me) at random if I can
	if (scalar(@nonops) > 0){
	    # this is ugly ...
	    #       my $victim=$mynick;
	    #       while($victim eq $mynick){
	    #           $victim = $nonops[rand @nonops]->{nick};
	    #           Irssi::print("It is $victim.");
	    #           if(scalar(@nonops) eq 1 and $victim eq $mynick){
	    #               break;
	    #           }
	    #       }
	    my $victim = $nonops[rand @nonops]->{nick};
	    Irssi::print("It is $victim.");
	    $server_rec->command("MODE $place +o-o $victim $mynick");
	} else {
	    $server_rec->command("MODE $place -o $mynick");
	}

    }
    #   #return unless defined $nick_text;      # happens if the part was us
    #   no warnings;
    #   my $channel_rec = $server_rec->channel_find($channel_text);
    #   use warnings;
    #   return unless defined $channel_rec;
    #   my $nick_rec = $channel_rec->nick_find($nick_text);
    #   partem($channel_rec, $nick_rec);
}

Irssi::signal_add_first('message irc mode', 'message_mode');
