package config;

use warnings;
use strict;
use autodie;

use server;
use pxelinux;
use client;
use file;
use ssh;
use upstream;

use File::Slurp;

our $mounted;

our $server;
our $server_ip;

sub available { qw/
	katalog debian_live webconverger
	debirf tinycore nfsroot
	openvz printer wrt
	clonezilla ubuntu memdisk vyatta android
	systemrescue
	memtest
/ };

sub debian_live {
	my ($ip) = @_;

	my $from = 'http://cdimage.debian.org/cdimage/release/current-live/i386/web/';
	my $variant = 'standard';

	my $dir = upstream::files $from => 'MD5SUMS';

	my ( $vmlinuz, $initrd, $squashfs );
	
	my @md5sum = read_file "$dir/MD5SUMS";

	foreach ( @md5sum ) {
		$vmlinuz = $1 if m/\s+(\S*vmlinuz\S*)/;
		$initrd = $1 if m/\s+(\S*$variant\S*initrd\S*)/;
		$squashfs = $1 if m/\s+(\S*$variant\S*\.squashfs)$/;
		warn "# MD5SUM: $_\n";
	}

	upstream::files $from => $vmlinuz, $initrd, $squashfs;

	my $hostname = client::conf( $ip => 'hostname' ) || 'debian-live';

	# FIXME drop in shell because users doesn't work in current image
	my $custom_init = 'init=/bin/hash';

	if ( my $custom_squashfs = client::conf( $ip => 'squashfs' ) ) {
		$squashfs = $custom_squashfs;
		$custom_init = '';
	}

	pxelinux::config_for_ip( $ip, qq{

default debian_live
label debian_live
	kernel $vmlinuz
	append initrd=$initrd fetch=http://$server_ip:7777/debian_live/$squashfs boot=live nopersistent hostname=$hostname union=aufs noprompt autologin username=user debug $custom_init
	});

}

=head1 webconverger

Webconverger - the opensource Web Kiosk

L<http://webconverger.org/>

=cut

sub _glob_first {
	my ( $dir, $path ) = @_;
	my @glob = glob "$dir/$path";
	my $first = $glob[0] || die "no $dir/$path";
	$dir   =~ s{iso/*$}{};
	$first =~ s{^\Q$dir\E}{}g;
	return $first;
}

sub webconverger {
	my ($ip) = @_;

	$mounted->{"webconverger/$ip"} ||= upstream::iso( 'http://download.webconverger.com/webc-6.2.iso' );

	my $hostname = client::conf( $ip => 'hostname' ) || 'webconverger';

	my $homepage = client::conf( $ip => 'webconverger/homepage'
		, default => "http://$server_ip:7777/client" );
	my $fetch    = client::conf( $ip => 'webconverger/fetch'
		, default => "http://$server_ip:7777/webconverger/iso/live/filesystem.squashfs" );

	my $mnt = "$server::base_dir/tftp/webconverger/iso";
	warn "# mnt: $mnt\n";
	my $kernel = _glob_first $mnt => 'live/vmlinuz*';
	my $initrd = _glob_first $mnt => 'live/initrd.img*';

	pxelinux::config_for_ip( $ip, qq{

default webconverger
label webconverger
	kernel $kernel
	append initrd=$initrd fetch=$fetch boot=live quiet nosudo splash video=vesa:ywrap,mtrr vga=788 nopersistent username=webc hostname=$hostname union=aufs homepage=$homepage locale=hr noprompt kioskresetstation=10

	});

}

sub katalog {
	my ($ip) = @_;
	$mounted->{"webconverger/$ip"} ||= upstream::iso( 'http://download.webconverger.com/webc-5.5.iso' );
	my $hostname = client::conf( $ip => 'hostname' ) || 'katalog';
	my $homepage = client::conf( $ip => 'webconverger/homepage' => "http://koha.ffzg.hr" );
	my $fetch    = client::conf( $ip => 'webconverger/fetch' => "http://$server_ip:7777/webconverger/custom.squashfs" );

	pxelinux::config_for_ip( $ip, qq{

default katalog
label katalog
	kernel iso/live/vmlinuz-2.6.30-backports.1-486
	append initrd=iso/live/initrd.img-2.6.30-backports.1-486 fetch=$fetch boot=live quiet nosudo splash video=vesa:ywrap,mtrr vga=788 nopersistent username=webc hostname=$hostname union=aufs homepage=$homepage locale=hr noprompt

	});

}
=head1 debirf

debirf is a system that will create diskless, all-in-ram images (kernel and initramfs) that boot entirely into ram and leave the user in a fully functional Debian system. 

L<http://cmrg.fifthhorseman.net/wiki/debirf>

=cut

sub debirf {
	my $ip = shift;

	upstream::iso( 'http://cmrg.mayfirst.org/debirf/debirf-rescue_lenny_2.6.26-1-686.iso' );

	pxelinux::config_for_ip( $ip, qq{

default linux
label linux
	kernel iso/vmlinuz-2.6.26-1-686
	append initrd=iso//debirf-rescue_lenny_2.6.26-1-686.cgz

	});
}

sub tinycore {
	my $ip = shift;
	upstream::iso( 'http://distro.ibiblio.org/pub/linux/distributions/tinycorelinux/3.x/release/tinycore-current.iso' );
	pxelinux::config_for_ip( $ip, qq{

default linux
label linux
	kernel iso/boot/bzImage
	append initrd=iso/boot/tinycore.gz

	});
}

sub clonezilla {
	my $ip = shift;
	upstream::iso( 'http://sourceforge.net/projects/clonezilla/files/clonezilla_live_alternative_testing/clonezilla-live-20100503-lucid.iso/download' );
	pxelinux::config_for_ip( $ip, qq{

default linux
label linux
	kernel iso/live/vmlinuz
	append initrd=iso/live/initrd.img boot=live union=aufs noswap noprompt vga=788 fetch=http://$server_ip:7777/clonezilla/iso/live/filesystem.squashfs

	});
}

sub ubuntu {
	my $ip = shift;
	upstream::iso( 'http://mirrors.us.kernel.org/ubuntu-releases/lucid/ubuntu-10.04-desktop-i386.iso' );

	my $export = "$server::base_dir/tftp/ubuntu/iso";
	my $exported = `exportfs | grep $export`;
	if ( $exported ne $export ) {
		warn "exportfs $exported\n";
		system "sudo exportfs -i -o rw,async,no_root_squash,no_subtree_check,fsid=999 $ip:$export";
	}
	pxelinux::config_for_ip( $ip, qq{

default linux
label linux
	kernel iso/casper/vmlinuz
	append initrd=iso/casper/initrd.lz boot=casper netboot=nfs nfsroot=$server_ip:$export --

	});
}

sub memdisk {
	my $ip = shift;

	my $dir = "$server::base_dir/tftp/memdisk";
	mkdir $dir unless -e $dir;

	symlink '/usr/lib/syslinux/memdisk', "$dir/memdisk" unless -e "$dir/memdisk";

	my $image = client::conf( $ip => 'memdisk.image' );

	if ( ! $image ) {
		$image = 'freedos.gz';
		upstream::mirror_file 'http://www.ibiblio.org/pub/micro/pc-stuff/freedos/files/distributions/unofficial/balder/balder10.imz' => "$dir/$image";
		warn "using $image [default FreeDOS]\n";
		symlink "$dir/$image", client::ip_path $ip . '/memdisk.image';
	} else {
		$image =~ s{^.+/tftp/memdisk/}{} && warn "using $image\n";
	}

	if ( my $kvm = client::conf $ip => 'kvm' ) {
		client::conf $ip => 'kvm.bin', 'qemu-system-i386'; # FIXME kvm doesn't seem to work
	}

	pxelinux::config_for_ip( $ip, qq{

default $image
label $image
	kernel memdisk
	append initrd=$image

	});
}

sub vyatta {
	my $ip = shift;
	upstream::iso( 'http://www.vyatta.com/downloads/vc6.1/vyatta-livecd_VC6.1-2010.08.20_i386.iso' );

	my $dir = "$server::base_dir/tftp/vyatta";
	symlink '/usr/lib/syslinux/memdisk', "$dir/memdisk" unless -e "$dir/memdisk";

	pxelinux::config_for_ip( $ip, qq{

default vyatta
label vyatta

	kernel iso/live/vmlinuz1
	append initrd=iso/live/initrd1.img boot=live nopersistent noautologin nonetworking nouser hostname=vyatta fetch=http://$server_ip:7777/vyatta/iso/live/filesystem.squashfs

	});
}

sub android {
	my $ip = shift;
	my $path = upstream::iso( 'http://android-x86.googlecode.com/files/android-x86-1.6-r2.iso' );

	my $dir = "$server::base_dir/tftp/android";
	symlink '/usr/lib/syslinux/memdisk', "$dir/memdisk" unless -e "$dir/memdisk";

	client::conf $ip => 'kvm.boot' => "n -cdrom $path";

	pxelinux::config_for_ip( $ip, qq{

default android-1.6-donut
label android-1.6-donut

	kernel iso/kernel
	append initrd=iso/initrd.img root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode quiet SRC= DATA= SDCARD= vga=788 DEBUG=1

	});
}


# http://www.sysresccd.org/Sysresccd-manual-en_PXE_network_booting
sub systemrescue {
	my $ip = shift;
	my $path = upstream::iso( 'http://sourceforge.net/projects/systemrescuecd/files/sysresccd-x86/1.6.1/systemrescuecd-x86-1.6.1.iso/download' );

	my $dir = "$server::base_dir/tftp/systemrescue";
	symlink '/usr/lib/syslinux/memdisk', "$dir/memdisk" unless -e "$dir/memdisk";

	client::conf $ip => 'kvm.boot' => "n -cdrom $path";

	pxelinux::config_for_ip( $ip, qq{

default systemrescue
label systemrescue

	kernel iso/isolinux/rescuecd
	append initrd=iso/isolinux/initram.igz dodhcp netboot=http://$server::ip:7777/systemrescue/iso/sysrcd.dat

	});
}

# http://www.memtest.org/
sub memtest {
	my $ip = shift;

	my $dir = "$server::base_dir/tftp/memtest";
	mkdir $dir unless -e $dir;
	symlink '/boot/memtest86+.bin', "$dir/memtest.bin" unless -e "$dir/memtest.bin";

	pxelinux::config_for_ip( $ip, qq{

default memtest
label memtest
	linux memtest.bin

	});
}

sub in_chroot {
	my ( $dir, $command ) = @_;
	write_file "$dir/tmp/inside.sh", $command;
	system "sudo chroot $dir sh -x /tmp/inside.sh";
}

sub nfsroot {
	my $ip = shift || die "no ip?";

	my $dist = 'lenny';
	$dist = 'squeeze';

	my $nfsroot = "$server::base_dir/tftp/nfsroot";
	my $debian_mirror = server::conf_default( 'debian_mirror', 'http://ftp.debian.org/debian' );

	if ( ! -e $nfsroot ) {
		system "sudo apt-get install nfs-kernel-server debootstrap aufs-modules-`uname -r` aufs-tools";
		mkdir $nfsroot;
	}

	my $debootstrap = "$nfsroot/debootstrap";

	if ( ! -e $debootstrap ) {

		system "sudo debootstrap --arch i386 $dist $debootstrap $debian_mirror";

		file::append "$debootstrap/etc/apt/sources.list.d/non-free.list", "deb $debian_mirror $dist non-free\n";
		in_chroot     $debootstrap => 'apt-get update';

		file::append "$debootstrap/etc/kernel-img.conf", "do_initrd = Yes\n";
		in_chroot     $debootstrap => 'apt-get -f install -y --force-yes locales linux-image-2.6-686 firmware-bnx2';

		# this can fails on some distros, so we run it alone
		in_chroot     $debootstrap => 'apt-get install -y --force-yes atl2-modules-2.6-686';
		file::append "$debootstrap/etc/initramfs-tools/modules", "atl2\n";

		file::change "$debootstrap/etc/initramfs-tools/initramfs.conf",  'BOOT=local' => 'BOOT=nfs';
		in_chroot     $debootstrap => 'update-initramfs -u';

	}

	my $export = "$nfsroot/$ip";
	my $br     = "$nfsroot/br/$ip";

	$mounted->{"nfsroot/$ip"} ||= `mount | grep $export`;

	if ( ! $mounted->{"nfsroot/$ip"} ) {
		warn "mounting $export";

		mkdir "$nfsroot/br"	unless -e "$nfsroot/br";
		mkdir $br			unless -e $br;
		mkdir $export		unless -e $export;

		system "sudo mount -t aufs -o br:$br:$debootstrap none $export";
		system "sudo exportfs -i -o rw,async,no_root_squash,no_subtree_check,fsid=999 $ip:$export";
	
	}

	my $exported = `exportfs | grep $export`;
	if ( $exported ne $export ) {
		warn "exportfs $exported\n";
		system "sudo exportfs -i -o rw,async,no_root_squash,no_subtree_check,fsid=999 $ip:$export";
	}

	my $hostname = client::conf( $ip => 'hostname' ) || 'nfsroot';
	file::replace "$export/etc/hostname", $hostname;
	file::replace "$export/etc/hosts", "127.0.0.1\tlocalhost $hostname\n";
	file::replace "$export/etc/resolv.conf", "domain $server->{domain}\nnameserver $server->{ip}\n";
	file::replace "$export/etc/rsyslog.d/pxelator.conf", "*.*\t\@$server->{ip}\n";

	file::append "$debootstrap/etc/network/interfaces", qq{

auto lo
iface lo inet loopback

allow-hotplug eth0
iface eth0 inet dhcp

	};

	map {
		file::copy_once $_ => "$export/$_";
		file::append "$export/etc/rc.local", $_;
	} ( '/srv/sysadmin-cookbook/recepies/amt/serial-console.sh' );

	pxelinux::config_ip_boot( $ip, "$export/boot", "root=/dev/nfs nfsroot=$server->{ip}:$export ro ip=dhcp" );

}

sub openvz {
	my $ip = shift;
	ssh::shell( $ip, 'cat /proc/vz/veinfo', 'vzlist -a', 'uptime', 'free', 'df', 'zfs list' );
}
sub printer     {}
sub wrt         {}

sub for_ip {
	my $ip = shift || return;
	$server = server::as_hash_for $ip;
	$server_ip = $server->{ip} || die "no server ip";
	my $config = client::conf( $ip => 'config' ) || return;
	my $ret = eval $config . '($ip)'; # must be last
	if ( $@ ) {
		warn "ERROR in executing $config($ip): $@\n";
		$ret .= qq{<pre style="color:red">$@</pre>};
	}
	return $ret;
}

warn 'loaded';

1;
