#!/usr/bin/perl -w

use strict;
use esmith::ConfigDB;
use esmith::AccountsDB;
use File::stat;

my $c = esmith::ConfigDB->open_ro || die "Couldn't open ConfigDB\n";
my $a = esmith::AccountsDB->open_ro  || die "Couldn't open AccountsDB\n";

my $pydio = $c->get('pydio') || die "pydio entry is missing in the configuration database\n";
my $status = $pydio->prop('status') || 'disabled';
my $defaultIndexer = $pydio->prop('Indexer') || 'enabled';

exit(0) if ($status ne 'enabled');

# Generate a random ID for our requests
my @chars = ('a'..'z','A..Z','0'..'9');
my $id = '';
foreach (0..32){
    $id .= $chars[rand @chars];
}
foreach my $share ($a->get_all_by_prop(type => 'share')){
    $pydio = $share->prop('Pydio') || 'disabled';
    $indexer = $share->prop('PydioIndexer') || '';
    next if ($pydio ne 'enabled' || $indexer eq 'disabled' || ($indexer ne 'enabled' && $defaultIndexer ne 'enabled'));
    my $name = $share->key;
    # Check if the lock file is present and if it's too old (last index crashed ?)
    if (-e "/var/cache/pydio/indexes/.ajxp_lock-$name"){
        my $mtime = stat("/var/cache/pydio/indexes/.ajxp_lock-$name")->mtime;
        unlink </var/cache/pydio/indexes/.ajxp_lock-$name>
            if (time() - $mtime > 18000);
    }
    system('/usr/bin/sudo -u www /usr/bin/php -d max_execution_time=3600 /usr/share/pydio/cmd.php ' .
           '-u=RDiin175M40T0cYvXLARpAi+1TsSVkbksEDZ4KvwBuY= '.
           '-t=e71479ebc4365176d9f09fe957780024 -a=index '.
           '-r='.$name.' --secure_token='.$id.' --dir=/ --_method=put >/dev/null 2>&1');
    # In some cases, the lock file is not removed, make sure it's unlocked
    unlink </var/cache/pydio/indexes/.ajxp_lock-$name>;
}
# We should now restart OOo to release memory
if (-d '/var/service/ooo'){
    system('/usr/bin/sv t /service/ooo');
}
