package lxc;

use warnings;
use strict;
use autodie;

use file;

use Data::Dump qw/dump/;

sub create {
	my ( $hostname, $path, $ip, $netmask, $server_ip ) = @_;

	die "$path: $!" unless -d $path;

	file::append "$path/etc/initab" => "$_\n" foreach split(/\n/, qq|
z6:6:respawn:/sbin/sulogin
1:2345:respawn:/sbin/getty 38400 console
c1:12345:respawn:/sbin/getty 38400 tty1 linux
c2:12345:respawn:/sbin/getty 38400 tty2 linux
c3:12345:respawn:/sbin/getty 38400 tty3 linux
c4:12345:respawn:/sbin/getty 38400 tty4 linux
	|);

	file::append '/etc/fstab' => 'cgroup /cgroup cgroup rw 0 0' && mkdir '/cgroup';
	system "mount /cgroup";

	system "lxc-stop    --name $hostname";
	system "lxc-destroy --name $hostname";

	file::replace "$path/etc/hostname" => $hostname;
	file::append  "$path/etc/hosts"    => "$ip $hostname";

	file::replace "$path/etc/network/interfaces" => qq|
auto eth0 lo

iface lo inet loopback

iface eth0 inet static
    address $ip
    netmask $netmask
    gateway $server_ip
	|;

	file::replace "$path/etc/resolv.conf" => "nameserver $server_ip";

	my $conf = "/virtual/$hostname.conf";

	file::replace $conf => qq|
lxc.utsname = $hostname
lxc.tty = 4
lxc.pts = 1024
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = virtual
lxc.network.name = eth0
lxc.network.mtu = 1500
#lxc.mount = MNTFILE
lxc.rootfs = $path
lxc.cgroup.devices.deny = a
# /dev/null and zero
lxc.cgroup.devices.allow = c 1:3 rwm
lxc.cgroup.devices.allow = c 1:5 rwm
# consoles
lxc.cgroup.devices.allow = c 5:1 rwm
lxc.cgroup.devices.allow = c 5:0 rwm
lxc.cgroup.devices.allow = c 4:0 rwm
lxc.cgroup.devices.allow = c 4:1 rwm
# /dev/{,u}random
lxc.cgroup.devices.allow = c 1:9 rwm
lxc.cgroup.devices.allow = c 1:8 rwm
lxc.cgroup.devices.allow = c 136:* rwm
lxc.cgroup.devices.allow = c 5:2 rwm
# rtc
lxc.cgroup.devices.allow = c 254:0 rwm
	|;

	system "lxc-create --name $hostname --rcfile $conf";

	warn "created $hostname $ip $path";
}

warn 'loaded';

1;
