Created
September 28, 2011 02:14
-
-
Save DamianZaremba/1246820 to your computer and use it in GitHub Desktop.
POC for updating files as needed from an external source
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use Digest::MD5; | |
use Cwd 'abs_path'; | |
my $base_dir = './testdata/'; | |
my $updates = 0; | |
# This is neater | |
sub hexdigest_file { | |
open(my $fh, shift); | |
binmode($fh); | |
my $checksum = Digest::MD5->new->addfile(*$fh)->hexdigest; | |
close($fh); | |
return $checksum; | |
} | |
sub write_config { | |
my($path, $entry) = @_; | |
open(my $fh, '>' . $path); | |
print $fh $entry->{'raw'}; | |
close($fh); | |
# Check the checksum matches | |
open(my $cfh, shift); | |
binmode($cfh); | |
my $new_checksum = Digest::MD5->new->addfile(*$cfh)->hexdigest; | |
my $entry_checksum = $entry->{'checksum'}; | |
close($cfh); | |
if($new_checksum ne $entry_checksum) { | |
print "Checksum mismatch for $path\n"; | |
} | |
} | |
# This is temp - it would get pulled from the API really | |
my $api_data = { | |
'data' => { | |
'abc' => { | |
'checksum' => "86fb269d190d2c85f6e0468ceca42a20", | |
'raw' => "Hello world!", | |
}, | |
}, | |
}; | |
print "Starting\n"; | |
# Loop though the directory | |
opendir( my $dh, $base_dir ); | |
foreach my $path ( readdir($dh) ) { | |
# Deal with the special entries | |
next if($path eq '.' || $path eq '..'); | |
# Make the path real | |
$path = abs_path($base_dir.$path); | |
# If this is a config file | |
if( $path =~ /((.*)\/)?(.*)\.conf$/ ){ | |
my $file = $3; | |
# $path - real path to file | |
# $file - how we reference the file in the API | |
# Check if this file needs deleting | |
# Lets check this first - don't need to touch | |
# the fs this way. | |
if( !$api_data->{'data'}->{$file} ) { | |
print "Should delete $path\n"; | |
unlink($path); | |
$updates++; | |
next; | |
} | |
# Check if we should update this file | |
# This means stat'ing the fs but saves a lot of writes | |
my $new_checksum = $api_data->{'data'}->{$file}->{'checksum'}; | |
my $current_checksum = hexdigest_file($path); | |
if( $new_checksum ne $current_checksum ) { | |
print "Should update $path\n"; | |
write_config($path, $api_data->{'data'}->{$file}); | |
$updates++; | |
next; | |
} | |
print "$path looks all good\n"; | |
} else{ | |
print "$path should not exist - NOT A CONFIG FILE\n"; | |
} | |
} | |
closedir( $dh ); | |
if($updates > 0) { | |
print "Should call a reload here\n"; | |
} | |
print "All done\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment