#!/usr/bin/perl -w
# System Format = Win32
#
##################################################################
##  Technical Services Scripty Thing
##  ================================
##  Author:  Xxx Xxxxxx - Technical Support Officer
##  Creation Date:  Friday, 4th August 2000.
##
##  This script is designed to better manage MARC records that
##  need to be sent to customers and a summary file to NLA.
##  Archive attributes will play a large role in the script,
##  in the future, it is hoped that the ability to automatically
##  send files via FTP to NLA and the DA FTP server for customers.
##                                                                
###################################################################

# Variable initialise
@InputDIR 	= ("./wuexport", "./cuexport");

# Find the last entrman mkdiry number for output dir
$NextOut = sprintf("%05d", FindLastOut('.') + 1);

# Find the files that need to be outputted in each dir

for my $dir (@InputDir) {
  mkdir "$dir/$NextOut", 0777 or die "Couldn't make dir "$dir/$Nextout": $!";
  CopyFiles($dir, "$dir/$NextOut", GrabFileList($dir));
}

sub CopyFiles {
  my $src = shift;
  my $dst = shift;
  foreach $file (@_) {
    next if $file !~ /\d/;
    next if $file !~ /\.txt$/;
    my $command = "cp $src/$file $dst/$file";
    system($command);
    print "$command\n";
  }
}

sub FindLastOut {
  my $OutputDIR = shift;
  opendir (FINDLASTOUT_OUT,$OutputDIR);
  my @Files = readdir (FINDLASTOUT_OUT);
  closedir (FINDLASTOUT_OUT);
  my $Highest = 0;
  foreach my $File (@Files) {
    next if $File !~ /^\d{5}/;
    my $n = substr($File, 0, 5);
    if ($n > $Highest) {
      $Highest = $n;
    }
  }
  return $Highest;
}

sub GrabFileList {
  my $dir = shift;
  opendir FILELISTDIR, $dir;
  my @files = grep { $_ ne '.' && $_ ne '..' } readdir FILELISTDIR;
  closedir FILELISTDIR;
  return @files;
}
