# $Id: autoaway+screen.pl,v 1.3 2008/06/05 21:26:22 cbellot Exp $
#
# autoaway+screen.pl: an irssi perl script (plugin)
#
# Usefull only for people using irssi+screen.
# It puts you away whenever your screen is detached and puts you back
# when screen is attached again.
#
# Commands:
# /set autoaway_message MESSAGE
#   to set the away message
# /set autoaway_screenname NAME
#   to define if you are attached to this specific screen name
# 
# Use:
# put this script in ~/.irssi/scripts
# launch a screen with a name like this :
#   screen -S irc1
# then launch irssi in this screen and load the script
#   /script load autoaway+screen.pl
# set autoaway_screenname to 'irc1'
#   /set autoaway_screenname irc1
# You can set autoaway_message if you wish

use Irssi 20020121.2020 ();
$VERSION = "0.1";
%IRSSI = (
	  authors     => 'Cyril Bellot',
	  contact     => 'jcpp\@users.sourceforge.net',
	  name        => 'autoaway+screen',
	  description => 'Makes you away when your screen is detached',
	  license     => 'GPL',
	  changed     => '$Date: 2008/06/05 21:26:22 $ ',
);

use Irssi::Irc;
use strict;

# How many seconds do we need to check if screen is attached ?
my $autoaway_timeout = 20;
# Default message if no one is set
my $default_message = "Unavailable...";

my $current_away;

#
sub is_screen_attached {
    # Look at screen list to see if we are attached
    my $nm = Irssi::settings_get_str("autoaway_screenname");
    open(SC, "screen -list|grep \"\.$nm\t\" |");
    my $sc = <SC>; close(SC);
    return ($sc =~ /Attached/);
}

#
sub away_check {
    if (is_screen_attached) {
	# If we are away, set us back
	if ($current_away) {
	    $current_away = 0;
	    my (@servers) = Irssi::servers();
	    my $server = $servers[0]; 
	    $server->command("/AWAY");
	}
    } else {
	# If we are not allready away, set us away
	if (!$current_away) {
	    $current_away = 1;
	    my (@servers) = Irssi::servers();
	    my $server = $servers[0]; 
	    my $msg = Irssi::settings_get_str("autoaway_message");
	    $msg = $default_message if ($msg eq "");
	    $server->command("/AWAY ".$msg);
	}
    }
}

Irssi::settings_add_str("misc", "autoaway_screenname", "irssi");
Irssi::settings_add_str("misc", "autoaway_message", $default_message);

$current_away = !&is_screen_attached();

my $timeout = Irssi::timeout_add($autoaway_timeout*1000, "away_check", "");

