package pxelinux;

use warnings;
use strict;
use autodie;

our $magic = 0xF100747E;

our $config_file; #= 'pxelinux.cfg/default';
our $path_prefix;
our $reboot_time; # 300 s

use server;
use client;
use File::Slurp;
use Carp qw/confess/;

sub config_for_ip {
	my ($ip,$config) = @_;
	confess "$ip not IP" unless $ip =~ m{^\d+\.\d+\.\d+\.\d+$};

	$path_prefix = (caller(1))[3];
	$path_prefix = (caller(2))[3] unless $path_prefix =~ m{config::};
	$path_prefix =~ s{config::}{} || warn "# caller isn't package config !";
	$path_prefix .= '/';

	warn "# $ip $path_prefix";

	my $dir = "$server::base_dir/tftp";
	$dhcpd::file = 'pxelinux.0';
	symlink "/usr/lib/syslinux/pxelinux.0", "$dir/$dhcpd::file" unless -e "$dir/$dhcpd::file";

	$dir .= "/$path_prefix";
	mkdir $dir unless -d $dir;

	mkdir "$dir/pxelinux.cfg" unless -e "$dir/pxelinux.cfg";

	$config_file = 'pxelinux.cfg/' . uc sprintf "%02x%02x%02x%02x", split(/\./, $ip, 4);
	warn "$ip config_file $config_file";

	my $path = "$dir/$config_file";
	write_file $path, $config;

	warn "# config: $path ", -s $path;

	return $config;
}

sub config_ip_boot {
	my ( $ip, $boot, $append ) = @_;

	my $default = client::conf $ip => 'default';
	my $config;

	foreach my $kernel ( glob "$boot/vmlinuz*" ) {
		my $ver = $1 if $kernel =~ m{vmlinuz(.+)};
		$default ||= 'boot' . $ver;

		$config .= qq{

label boot$ver
	kernel $ip/boot/vmlinuz$ver
	append initrd=$ip/boot/initrd.img$ver $append

		};
	}

	config_for_ip( $ip, qq{

default $default
prompt 1
timeout 30

$config

	});

}

1;
