PUB /

PerlBackupScript

use strict;
use warnings;

use File::Copy::Recursive qw(fcopy);
use Win32::File;

our $type;
our $backupdir;
my $startdir;


if (scalar(@ARGV) != 3) {
  die "Usage: $0 <inc|full> <startdir> <backupdir>\n";
}

if ($ARGV[0] =~ /^(inc|full)$/i) {
  $type = $ARGV[0];
}
else {
  die "Valid types are Inc or Full\nUsage: $0 <inc|full> <startdir>\n";
}

$startdir = $ARGV[1];
$backupdir = $ARGV[2];

Directory($startdir);

1;


sub Directory {
  my $dir = shift;
  if (opendir(DIR, $dir)) {
    my @dir = readdir(DIR) or warn "Can't access $dir: $!\n";
    foreach my $file (@dir) {
      my $fullfile = $dir.'\'.$file;
      if ($file eq '.' or $file eq '..') {
        next;
      }
      elsif (-d $fullfile) {
        Directory($fullfile);
      }
      else {
        if (CheckArchive($fullfile)) {
          if (Backup($fullfile)) {
            UnsetArchive($fullfile);
          }
          else {
            warn "Error backing up $fullfile\n";
          }
        }
      }
    }
  }
  else {
    warn "Can't access $dir: $!\n";
  }
}


sub CheckArchive {
  #Check if the Archive bit is set
  my $file = shift;
  my $attrs;

  if ($type =~ /full/i) {
    return 1;
  }
  else {
     Win32::File::GetAttributes($file, $attrs);
     if ($attrs & ARCHIVE) {
       return 1;
     }
     else {
       return 0;
     }
  }
}


sub UnsetArchive {
  #Unset the Archive bit
  my $file = shift;
  my $attrs;
  Win32::File::GetAttributes($file, $attrs);
  Win32::File::SetAttributes($file, $attrs & (~ ARCHIVE));
}


sub Backup {
  #Copy the file
  my $file = shift;
  my $dest;

  {
    ($file =~ /^\w:\(.*)/);
    $dest = $backupdir."\".$1;
  }
  #print "Backup $file to $dest\n";
  fcopy($file,$dest) or warn "Problem backing up $file: $!\n";