package kvm;

use warnings;
use strict;
use autodie;

use server;

use Data::Dump qw/dump/;

our $memory_size = 512;

# AC = private, AD = multicast, AE = local

our $nr = 0;

sub port {
	my $del = shift;
	my $port = 10000 + $nr;
	return join( $del, $server::ip, $port );
}

sub fork_if_active { qw/monitor/ }

use x11;

sub monitor {
	x11::xterm( "monitor $nr" => 'nc ' . port(' ') );
}

sub actions { qw/reset activate/ }

sub reset {
	my $sock = IO::Socket::INET->new( port(':') );
	print $sock "system_reset\n";
	close $sock;
}

sub activate {
	system "xdotool windowactivate `xdotool search --class kvm`"
}

sub start {
	my $nr = shift || 0;

	my $mac = sprintf('AC:DE:48:00:00:%02x', $nr);
	my $mon = port(':');

	my $ifname = 'kvm0';

#	system "ifconfig $ifname down";
#	system "brctl delif virtual $ifname";
#	system "tunctl -d $ifname";

	system "tunctl -t $ifname"; # -u $server::user
	system "ifconfig $ifname up";
	system "brctl addif virtual $ifname";

	my $kvm = qq|
		kvm -m $memory_size -net nic,macaddr=$mac
		-net tap,ifname=$ifname,script=no
		-boot n
		-monitor tcp:$mon,server,nowait
	|;
	#	-runas $server::user
	$kvm =~ s{\s+}{ }gs;

	warn $kvm;
	exec $kvm;

}

warn 'loaded';

1;
