package x11;

use warnings;
use strict;

use log;
use File::Slurp;

my @cols;

my $last_col = '';
open(my $rgb, '<', '/etc/X11/rgb.txt');
while(<$rgb>) {
	chomp;
	my $col = $1 if m{(\S+)\s*$};
	next unless $col =~ m{Light};
	push @cols, $col if $last_col ne $col;
	$last_col = $col;
}
close($rgb);

sub xterm {
	my ( $name, $cmd ) = @_;

	$name =~ s{\s+}{-}g;
	my $screenrc = "/tmp/$name.screenrc";

	my ($autodetach,$detach) = $ENV{DISPLAY} ? ('off','') : ( 'on', 'detach' );

	write_file $screenrc, qq|

autodetach $autodetach
altscreen off
defscrollback 10000
startup_message off

sessionname $name

screen -t $name $cmd
logfile $log::dir/$name.log
log on

$detach

|;

	my $screen = "screen -R $name -c $screenrc";
	my $exec;

	if ( $ENV{DISPLAY} ) {
		my $hash;
		$hash += ord($_) foreach ( split //, $name );
		my $fg = $cols[ $hash % $#cols ];
		$exec = "xterm -fg $fg -T '$name' -n '$name' -e '$screen'";
warn "XXXX $exec";
	} else {
		warn "system $screen";
		system $screen;
		return;
	}

	warn "exec $exec";
	exec $exec;
}

1;
