Posted to tcl by kostix at Wed Nov 01 00:23:51 GMT 2006view pretty

#! /usr/bin/perl
# Minimalistic start-up frontend for SCREEN.
# At first, asks the screen whether there're some lingering screen sessions.
# If there is none, just starts screen, otherwise asks the user
# to select desired session (or opt for creating a new one).
# Given the user choice, arranges to make the user connected to what he/she chose.

# v1.0, 06-Aug-2005, kostix. Initial version.

# TODO extract PTY and host from the screen's output, show them to the user.
# TODO (?) add options processing.

use strict;
use warnings;

open SCREENS, 'screen -ls 2>&1 |';

my (@screens, $complaint);
push @screens, [ '<make new session>', 'new' ];

while(<SCREENS>) {
	# $1 -> screen id, $2 -> mode:
	if (/^\s+(\d+).*\s+\((\w+)\)$/) {
		push @screens, [ $1, lc $2 ];
	} else {
		$complaint .= $_;
	}
}

my $ok = close SCREENS;
$ok >>= 8, die "screen -ls returned $ok and said: $complaint" unless $ok != 1;

exec 'screen' unless @screens; # just spawn screen making new session.

my $no = 0;
foreach my $ref (@screens) {
	my $id = $ref->[0]; my $state = $ref->[1];
	print "$no: $id -> $state\n";
	++$no;
}

require Term::ReadLine;
my $rl = Term::ReadLine->new('Screen Selector');

my $resp = undef;
while ('forever') {
	$resp = $rl->readline('Pick one or give EOF: ');
	
	exit 1 unless defined $resp; # bail out on EOF
	last if $resp =~ qr/^\d+$/;
	print "Never learned how to type a number?\n";
}

exec 'screen' if $resp == 0; # user has opted for new session

# Reattach to a running session:
my @spell = ('screen');
push @spell, '-d' if $screens[$resp][1] eq 'attached';
push @spell, '-r', $screens[$resp][0];
exec @spell;