mkbasedir and conf_value which knows how to read symlinks from filesystem correctly
authorDobrica Pavlinusic <dpavlin@rot13.org>
Sat, 15 Aug 2009 13:44:13 +0000 (13:44 +0000)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Sat, 15 Aug 2009 13:44:13 +0000 (13:44 +0000)
lib/PXElator/client.pm

index f090591..e07004e 100644 (file)
@@ -4,13 +4,35 @@ use warnings;
 use strict;
 use autodie;
 
-use server;
 use File::Slurp;
 use Net::Ping;
+use Carp qw/confess/;
+
+use server;
 use format;
 
+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 {
+               confess "$path not file or symlink";
+       }
+       return $value;
+}
 
 sub conf {
        my $ip  = shift;
@@ -27,19 +49,18 @@ sub conf {
        $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 {
+               confess "conf $name";
        }
        return $value;
 }
@@ -90,8 +111,7 @@ sub ip_from_mac($) {
                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";
        }
@@ -101,7 +121,7 @@ sub ip_from_mac($) {
 
 sub mac_from_ip($) {
        my $ip = shift;
-       return read_file ip_path($ip, 'mac');
+       conf_value ip_path($ip, 'mac');
 }
 
 sub change_ip($$) {