--- lib/PXElator/client.pm 2009/08/12 23:59:01 208 +++ lib/PXElator/client.pm 2009/08/25 15:00:20 286 @@ -4,13 +4,36 @@ use strict; use autodie; -use server; use File::Slurp; use Net::Ping; + +use server; use format; +our $debug = $server::debug; + +sub mkbasedir { + my $path = shift; + $path =~ s{(^.*)/[^/]+$}{$1}; + mkdir $path unless -d $path; + return $path; +} + sub mac_path { $server::conf . '/mac/' . $_[0] } sub ip_path { $server::conf . '/ip/' . join('/', @_) } +sub conf_value { + my $path = shift; + my $value; + if ( -l $path ) { + $value = readlink $path; + $value =~ s{.*/([^/]+)$}{$1}; + } elsif ( -f $path ) { + $value = read_file $path; + } else { + warn "W: $path not file or symlink\n"; + } + return $value; +} sub conf { my $ip = shift; @@ -27,29 +50,22 @@ $path .= '/' . $name; if ( defined $value ) { + mkbasedir $path; write_file $path, $value; warn "update $path = $value"; } elsif ( ! -e $path && defined $default ) { + mkbasedir $path; 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; - } + } elsif ( -f $path ) { + $value = read_file $path; + } else { + warn "# $name missing $path\n" if $debug; } return $value; } -sub mac { - my $ip = shift; - my $mac = client::conf( $ip, 'mac' ) || return ''; - format::mac( $ip, @_ ); -} - sub next_ip($) { my $mac = shift; @@ -68,13 +84,20 @@ warn "next_ip $ip\n"; - mkdir ip_path($ip); - - symlink ip_path($ip), mac_path($mac); - write_file ip_path($ip,'mac'), $mac; + save_ip_mac( $ip, $mac ); return $ip; +} + +sub save_ip_mac { + my ($ip,$mac) = @_; + mkdir ip_path($ip) unless -e ip_path($ip); + + my $mac_path = mac_path($mac); + unlink $mac_path if -l $mac_path; # XXX audit? + symlink ip_path($ip), $mac_path; + write_file ip_path($ip,'mac'), $mac; } sub ip_from_mac($) { @@ -94,8 +117,7 @@ symlink ip_path($ip), $mac_path; warn "I: upgrade to mac symlink $mac_path\n"; } elsif ( -l $mac_path ) { - $ip = readlink $mac_path; - $ip =~ s{^.+/([^/]+)$}{$1}; + $ip = conf_value $mac_path; } else { die "$mac_path not file or symlink"; } @@ -105,7 +127,7 @@ sub mac_from_ip($) { my $ip = shift; - return read_file ip_path($ip, 'mac'); + conf_value ip_path($ip, 'mac'); } sub change_ip($$) {