package network;

use warnings;
use strict;

use File::Slurp;

use server;
use ip;

sub ifconfig {
	my $dev = shift;
	`/sbin/ifconfig $dev`
}

sub setup {

	if ( my $dev = $ENV{DEV} ) {
		warn "W: running under device $dev, not configuring network\n";
		return;
	}

	my $ifconfig = ifconfig('virtual');
	if ( $ifconfig !~ m{UP} ) {
		system "brctl addbr virtual";
		system "brctl setfd virtual 0";
		system("/sbin/ifconfig virtual $server::ip netmask $server::netmask") == 0 || warn "W: $!";
	} else {
		warn "using existing virtual configuration\n$ifconfig\n";
	}
	if ( my $dev = ip::default_route_dev() ) {
		system "sudo sysctl -w net.ipv4.ip_forward=1";
		my $network = ip::from_int( ip::to_int($server::ip) & ip::to_int($server::netmask) );
		warn "# network $network";
		system "sudo iptables -t nat -L POSTROUTING -n | grep $network || sudo iptables -t nat -A POSTROUTING -s $server::ip/$server::netmask -o $dev -j MASQUERADE";
		warn "masquarade to $dev";
	}
}

sub tap {

	if ( my $dev = $ENV{DEV} ) {
		warn "W: running under device $dev, not configuring tap0\n";
		return;
	}

	if ( $server::ip !~ m{^172} ) {
		warn "W: server ip mismetch, not configuring tap0\n";
		return;
	}

	my $interfaces = read_file '/etc/network/interfaces';

	if ( $interfaces !~ m{tap0}s ) {

		system "sudo apt-get install -y vde2";

		write_file '/tmp/interfaces', qq{

# added by PXElator
iface tap0 inet static
	address $server::ip
	netmask $server::netmask
	vde2-switch -
	# setup NAT for vde network
	post-up sysctl -w net.ipv4.ip_forward=1
	post-up iptables -t nat -A POSTROUTING -s $server::ip/$server::netmask -o wlan0 -j MASQUERADE

		};

		system q|sudo sh -c 'cat /tmp/interfaces >> /etc/network/interfaces'|;
		system q|sudo sh -c 'usermod -G vde2-net -a $SUDO_USER'|;

	}

	my $ifconfig = ifconfig('tap0');
	if ( $ifconfig =~ m{UP} ) {
		 $ifconfig =~ m{$server::ip}s && return 'up';
		system("sudo /sbin/ifconfig tap0 $server::ip netmask $server::netmask") == 0 && return "ip changed $server::ip";
		die "can't change IP address of tap0 to $server::ip";
	} else {
		die "bring interface up with: sudo ifup tap0\n";
	}
}

1;
