#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2010 Firewall Services
# daniel@firewall-services.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#----------------------------------------------------------------------


use esmith::AccountsDB;
use File::Find;
use File::stat;

my $a = esmith::AccountsDB->open_ro or die "Error opening accounts DB\n";

foreach my $share ($a->get_all_by_prop(type=>'share')){
    my $key = $share->key;
    my $recycle = $share->prop('RecycleBin') || 'disabled';
    our $retention = $share->prop('RecycleBinRetention') || 'unlimited';
    # Skip the share if recycle bin is disabled or if retention is not limited
    next if (($recycle eq 'disabled') || ($retention eq 'unlimited'));
    # Convert retention in seconds
    $retention = 60*60*24*$retention;
    my $dir = $share->prop('RecycleBinDir') || 'Recycle Bin';
    # Skip if dir contains ./
    next if $dir =~ m#(\./)#;
    finddepth(\&remove, "/home/e-smith/files/shares/$key/files/$dir/");
}

sub remove{
    # Remove files with last modification older than $retention
    if ( -f ){
        my $mtime = stat($_)->mtime;
        (time() - $mtime > $retention) && unlink($_);
    }
    # Remove empty directories
    elsif ( -d ){
        (scalar <"$_/*">) || rmdir("$_");
    }
}

