package log;

use warnings;
use strict;
use autodie;

use server;

our $dir = "$server::base_dir/log";
mkdir $dir unless -e $dir;

foreach ( glob("$dir/pxelator.*.log") ) {
	warn "unlink $_ ", -s $_;
	unlink $_;
}

my $mac_dir = "$dir/mac";
mkdir $mac_dir unless -e $mac_dir;

use Time::HiRes qw/time/;
my $start_t = time();

sub mac {
	my ( $mac, $message ) = @_;
	print "MAC $mac $message\n";
	open(my $fh, '>>', "$mac_dir/$mac");
	print $fh time() - $start_t, "\t$message\n";
	close($fh);
}

our $mac_pos;

use File::Slurp;

sub mac_changes {
	my $mac = shift;

	my @changes;

	foreach my $mac_path ( sort glob("$mac_dir/*") ) {

		open(my $fh, '<', $mac_path);

		my $pos = $mac_path;
		$pos =~ s{/([^/]+$)}{/\.$1\.pos};
		my $mac = uc($1);
		$mac =~ s{(..)}{$1:}g;
		$mac =~ s{:$}{};
		seek $fh, read_file($pos), 0 if -e $pos;

		while(<$fh>) {
			chomp;
			push @changes, "$_\t$mac";
		}

		warn "pos $pos ",tell($fh);
		write_file $pos, tell($fh);
	}

	return @changes;
}

1;
