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

sub nr { $ENV{nr} || 0 };

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

sub fork_if_active { qw/monitor serial/ }

use x11;

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

sub serial {
	x11::xterm( 'serial ' . nr() => 'nc ' . port(11000,' ') );
}

sub actions { qw/reset activate/ }

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

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

sub start {
	my $nr = $ENV{nr} || 0;

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

	my $ifname = 'kvm' . $nr;

	warn "# kvm start $nr $mac $mon $ser $ifname";

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

	my $ifconfig = `/sbin/ifconfig $ifname`;

 	# FIXME tunctl -u $server::user
	system "tunctl -t $ifname"
		unless $ifconfig =~ m{$ifname};
	system "ifconfig $ifname up"
		unless $ifconfig =~ m{UP};
	system "brctl addif virtual $ifname"
		unless `brctl show` =~ m{$ifname};

	my $ip = client::ip_from_mac $mac;

	my $name = client::conf( $ip, 'hostname' );
	$name ||= $nr;

	my $boot = client::conf( $ip, 'kvm.boot' ) || 'n'; # network by default

	my $kvm = qq|
		kvm
		-name "$name"
		-m $memory_size -net nic,macaddr=$mac
		-net tap,ifname=$ifname,script=no
		-boot $boot
		-monitor tcp:$mon,server,nowait
		-serial  tcp:$ser,server,nowait
	|;

	$kvm .= ' -vnc ' . port(0,':') unless $ENV{DISPLAY};

	#	-runas $server::user
	$kvm =~ s{\s+}{ }gs;

	warn $kvm;
	exec $kvm;

}

sub nr_from_mac {
	my $mac = shift;
	$mac =~ s{^.+:([0-9a-f]{2})$}{hex($1)}e;
	$mac;
}

sub next_nr {
	my @kvms = glob "$server::conf/mac/AC:DE:48:00:00:*";
	my $nr = nr_from_mac( pop @kvms );
	return $nr + 1;
}

warn 'loaded';

1;
