# Copyright 2016 Mirko Tietgen <mirko@abunchofthings.net>
# License: AGPL v3 or later
#
# Simple batch "upload" script for Koha
#
# Creates sql to insert Koha database entries.
# Creates a lookup file for filename<>hash.
# Renames the files in the way Koha expects them.

use Digest::MD5;
use Encode;

# taken from Upload.pm
use constant BYTES_DIGEST => 2048;

# use borrower id of your file owner
my $owner = 51;

# sql to be added to koha db
my $sqlfile = "upload-files.sql";

# lookup file with 'filename,hash'
# use with catmandu or other script to create correct links in your MARC records
my $catmandufile = "upload-lookup.csv";

# the directory your files are in
# use the same locally as on the koha server
# create an authorized value in UPLOAD category for the directory
# the script assumes directory and upload category are the same
my $dir = 'directory';

my $filesize;

opendir(DIR, $dir) or die $!;

while (my $file = readdir(DIR)) {

    # skip some files. the ones i wanted all started with 'file'.
    # also prevented multiple hashing and renaming when working on a lot of files
    # you would want to skip '.' and '..' at least
    if ( $file !~ /^file/ ) {
        print "skipping $file\n";
        next;
    }

    open FILE, $dir . '/' . $file or die $!;
        read(FILE,$block,2048);
        $filesize = -s FILE;
        print "reading $file, size $filesize bytes\n";
    close FILE;

    my $str    = $file . $owner . '' . $dir . $block;
    my $hash   = Digest::MD5::md5_hex( Encode::encode_utf8( $str ) );

    # add to SQL file
    
    open SQL, '>>', $sqlfile or die $!;
        print SQL "INSERT INTO `uploaded_files` (`hashvalue`, `filename`, `dir`, `filesize`, `uploadcategorycode`, `owner`, `public`, `permanent`)\nVALUES ('$hash','$file',$dir,$filesize,$dir,$owner,1,1);\n";
    close SQL;
    
    # add to lookup file
    
    open CATMANDU, '>>', $catmandufile or die $!;
        print CATMANDU "$file,$hash\n";
    close CATMANDU;
    
    # rename file

    rename $dir . '/' . $file,$dir . '/' . $hash . '_' . $file;

}