#!/usr/bin/perl

use strict;
use warnings;

## use root's library
use lib qw(/root/usr/share/perl/5.12.4/);

use Data::Dumper;
use DBI;
use File::Slurp;
use File::Temp qw/ tempfile tempdir /;
use MySQL::Config qw(parse_defaults);


## version string
my $omeka='omeka-1.4.1';

## tables that need rows deleting for clean
## this may be dependent on the version, and on plugins
my $itofi_tables;
#$itofi_tables->{'omeka_csv_import_imported_items'}=1;
#$itofi_tables->{'omeka_csv_import_imports'}=1;
$itofi_tables->{'omeka_items'}=1;
$itofi_tables->{'omeka_tags'}=1;
$itofi_tables->{'omeka_taggings'}=1;
$itofi_tables->{'omeka_csv_import_imported_items'}=1;
$itofi_tables->{'omeka_files'}=1;
$itofi_tables->{'omeka_element_texts'}=1;
$itofi_tables->{'omeka_entities_relations'}->{'type'}='item';
$itofi_tables->{'omeka_processes'}->{'status'}='completed';


## the archives directory
my $archive_dir=$ENV{'HOME'}.'/omeka/archive';

## which user am I running as?
my $whoami=`whoami`;
chomp $whoami;

## open database connection
my $dbh=&open_mysql($whoami);
$dbh->do("use $whoami");

## delete all files
system("find $archive_dir -type f ! -name index.html -exec rm -f {} \\;");
## sanity check, find tables, in case there are some in the itofi
## tables that are not present in this installation
my $tables=&find_omeka_tables();
&clean_omeka_tables_related_to_itofis($tables);
$dbh->disconnect;

##### the end #####

## 
sub clean_omeka_tables_related_to_itofis {
  my $tables=shift;
  foreach my $table (keys %$itofi_tables) {
    my $command='';
    if(not defined($tables->{$table})) {
      next;
    }
    if(ref $itofi_tables->{$table}) {
      foreach my $field (keys %{$itofi_tables->{$table}}) {
        my $value=$itofi_tables->{$table}->{$field};
        my $command="DELETE FROM $table WHERE $field='$value'";
        print "$command\n";
        $dbh->do($command);
      }
    }
    else {
      $command="DELETE FROM $table";
      print "$command\n";
      $dbh->do($command);
    }
  }
}

## find all tables
sub find_omeka_tables {
  my $tables;
  my $sth_show=$dbh->prepare("show tables");
  my $rv=$sth_show->execute();
  while(my $row = $sth_show->fetchrow_arrayref) {
    my $table=$row->[0];
    if(not $table=~m|^omeka_|) {
      next;
    }
    $tables->{$table}=1;
  }
  return $tables;
}

## open mysql
sub open_mysql {
  my %cfg = parse_defaults "my", qw(client);
  my $dbh = DBI->connect("DBI:mysql:", $cfg{'user'}, $cfg{'password'}) or die;
  my $sth = $dbh->prepare("SET collation_connection = utf8_general_ci");
  my $rv = $sth->execute();
  return $dbh;
}
