#!/usr/bin/perl -w
#################################

#fvwm-screen-menu.pl
#Original by: jsosic
#
#Modified by Dennis Katsonis to add Tmux support.
#################################

use Shell qw(screen tmux grep hostname);

$hostname = hostname("-s");
#regexps rule :wink:
$hostname=~s/\s//g;

#Get list of detached/attached screen sessions and hostname


# SCREEN SECTION - Delete this section if you don't want screen support
$s_detached_sessions = `screen -list | grep Detached`;
$s_attached_sessions = `screen -list | grep Attached`;

$s_detached_sessions=~s/\(.*\)|(|Detached|\.$hostname)//g;
$s_attached_sessions=~s/\(.*\)|(|Attached|\.$hostname)//g;

print " + \"SCREEN\" Title\n";

#Add some general stuff…
print " + \"New Session\" Exec exec xterm -n screen -e screen \n";
print " + \"Reattach first\" Exec exec xterm -n screen -e screen -d -RR \n";


#put separator if there are detached screens…
if ($s_detached_sessions ne ""){
	print " + \"Screen Detached\" Title\n";
}


#Finally, here’s what we came for.
@ls_detached_sessions = split /\n+/, $s_detached_sessions;
foreach my $session (@ls_detached_sessions){
	$session=~s/^\s+|\s+$//g;
	print " + \"$session\" Exec exec xterm -n screen -e screen -r \"$session\"\n";
}


#put separator if there are attached screens…
if ($s_attached_sessions ne ""){
	print " + \"Screen Attached\" Title\n";
}

#Little last minute addition: Attached sessions
@ls_attached_sessions = split /\n+/, $s_attached_sessions;
foreach my $session (@ls_attached_sessions){
	$session=~s/^\s+|\s+$//g;
	print " + \"$session\" Exec exec xterm -n screen -e screen -d -t \"$session\"\n";
}


# TMUX SECTION - Delete this section if you don't want tmux support


$t_detached_sessions = `tmux list-sessions -F '#{session_name} #{?session_attached,Attached,Detached}' | grep Detached`;
$t_attached_sessions = `tmux list-sessions -F '#{session_name} #{?session_attached,Attached,Detached}' | grep Attached`;
$t_detached_sessions=~s/()|(|Detached|^\s+)//g;
$t_attached_sessions=~s/()|(|Attached|^\s+)//g;

print " + \"TMUX\" Title\n";

print " + \"New Session\" Exec exec xterm -n tmux -e tmux \n";
print " + \"Reattach first\" Exec exec xterm -n tmux -e tmux attach-session \n";

#put separator if there are detached screens…
if ($t_detached_sessions ne ""){
	print " + \"Tmux Detached\" Title\n";
}


@ls_t_detached_sessions = split /\n+/, $t_detached_sessions;
foreach my $session (@ls_t_detached_sessions){
	$session=~s/^\s+|\s+$//g;
	print " + \"$session\" Exec exec xterm -n tmux -e tmux attach-session -t \"$session\"\n";
}


#put separator if there are attached screens…
if ($t_attached_sessions ne ""){
	print " + \"Tmux Attached\" Title\n";
}

#Little last minute addition: Attached sessions
@ls_t_attached_sessions = split /\n+/, $t_attached_sessions;
foreach my $session (@ls_t_attached_sessions){
	$session=~s/^\s+|\s+$//g;
	print " + \"$session\" Exec exec xterm -n tmux -e tmux attach-session -t \"$session\"\n";
}
