package client;

use warnings;
use strict;
use autodie;

use server;
use File::Slurp;
use Net::Ping;

sub conf {
	my $ip  = shift;
	my $name = shift;
	my ( $default, $value );
	if ( $#_ == 0 ) {
		$value = shift;
	} elsif ( $#_ == 1 && $_[0] eq 'default' ) {
		$default = $_[1]
	}

	my $path ="$server::conf/ip/$ip";
	mkdir $path unless -d $path;
	$path .= '/' . $name;

	if ( defined $value ) {
		write_file $path, $value;
		warn "update $path = $value";
	} elsif ( ! -e $path && defined $default ) {
		write_file $path, $default;
		warn "default $path = $default";
		$value = $default;
	} elsif ( -e $path ) {
		if ( -l $path ) {
			$value = readlink $path;
			$value =~ s{.*/([^/]+)$}{$1};
		} else {
			$value = read_file $path;
		}
	}
	return $value;
}

sub mac {
	my ( $ip, $op ) = @_;
	$op ||= 'html';
	my $mac = client::conf( $ip, 'mac' );
	return '' unless $mac;
	$mac =~ s{(..)}{$1:}g;
	$mac =~ s{:$}{};
	$mac = qq|<tt>$mac</tt>| if (caller(1))[3] =~ m{^httpd} && $op ne 'clean';
	return uc($mac);
}

sub next_ip {

	my $p = Net::Ping->new;

	my $prefix = $server::ip;
	$prefix =~ s{\.\d+$}{.};
	my $addr = $server::ip_from || die;
	my $ip = $prefix . $addr;

	while ( -e "$server::conf/ip/$ip" || $p->ping( $ip, 0.7 ) ) {
		$ip = $prefix . $addr++;
		die "all addresses allocated!" if $addr == $server::ip_to;
		warn "skip $ip\n";
	}

	warn "next_ip $ip\n";
	return $ip;

}

1;
