#!/usr/bin/env perl
# is-attached -- check whether a Mosh session is currently attached to a live client
use Sys::Utmp qw(:constants);

use constant {
	EX_ATTACHED => 0,
	EX_DETACHED => 1,
};

my $verbose = ($ARGV[0] eq "-v");

my @ttys;

if (open(my $fh, "-|", "tmux", "list-clients", "-t", "irc")) {
	@ttys = map {m[^/dev/(.+?): ] and $1} <$fh>;
	close($fh);
}

if (@ttys) {
	# tmux session has clients attached
	# ignore those belonging to detached mosh sessions
	my %ttys = map {$_ => 1} @ttys;
	my $re = qr/^mosh \[\d+\]$/;
	my $utmp = Sys::Utmp->new;
	while (my $ut = $utmp->getutent) {
		my $t = $ut->ut_line;
		if ($ut->ut_type == USER_PROCESS && $ttys{$t}) {
			# this belongs to our tmux session
			my $h = $ut->ut_host;
			if ($h =~ $re) {
				# this is a detached mosh session, ignore
				print "line $t is detached: $h\n" if $verbose;
				delete $ttys{$t};
			} else {
				print "line $t is attached: $h\n" if $verbose;
			}
		}
	}
	@ttys = keys %ttys;
}

exit(@ttys ? EX_ATTACHED : EX_DETACHED);
