#!/usr/bin/perl
#------------------------------------------------------------ 
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------ 
use strict;

use Data::Dumper;
use File::Path;

use lib '/app/tools/common/lib';
use Common::DB::Item::Client;

# This script will copy (not move) all of the royalty statements from their current location
# to the new location on the shared drive.
#


my $origPath = '/app/data/royalty_statements/';
my $newPath = '/app/shared/royalty_statements/';

my @statementTypes = `ls -t $origPath`;

my $appSingleton = Common::RSApp->new( clientID => 0 );

foreach my $type (@statementTypes)
{
    chomp($type);
    if ($type)
    {
        my $clientPath = $origPath.$type;      
        
        my @clientDirs = `ls $clientPath`;
        
        foreach my $clientID (@clientDirs)
        {
            
            chomp($clientID);
            # Translate client id to client name clean
            #
            my $client = Common::DB::Item::Client->Lookup(client_id => $clientID);
            if ($client)
            {
                my $clientName = $client->client_name_clean;        
                chomp($clientName);

		print STDERR "Copying statements for $clientName\n";
                          
                # Now we need to do some recursive copying from the old dir to the new one
                #        
                my $oldDir = $clientPath."/".$clientID."/*";
                my $newDir = $newPath.$type."/".$clientName;
                
                # First, create the new directory.
                #
                if (! -d $newDir)
                {
                    mkpath($newDir) or die "ERROR: Unable to create path $newDir: $!\n";
                }       
                
                # Now, put stuff it.
                #
                `cp -r $oldDir $newDir`; 
                
                # And finally, add the semaphores
                #
                my @runDirs = `ls $newDir`;
                
                foreach my $run (@runDirs)
                {
                    chomp($run);

                    _createEmptyFile($newPath.$type."/".$clientName."/".$run."/COMPLETE"); 
                    _createEmptyFile($newPath.$type."/".$clientName."/".$run."/TEXT_COMPLETE");                
                    
                }              
                
            }       
            
        }
	# !! This didn't work.
        # Oh, and make sure everything is writable by the group
        #
        #`chmod -R g+w $newPath`;        
        
    }
} 


sub _createEmptyFile {
    eval {
        open my $fh, '>', $_[0]
        or die "Cannot create $_[0]: $!\n";
        close $fh or die "Cannot close $_[0]: $!\n";
    };
    return $@;
} 
