#!/usr/bin/perl -w

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell
use strict;

=pod

=head1 NAME

bric_clean_tmp - Bricolage temp directory maintenance

=head1 SYNOPSIS

This script is designed to be run from cron. To run it nightly at 2am put a like
like this in the crontab for the web server user (often "nobody"):

    0 2 * * * /usr/local/bin/bric_clean_tmp

=head1 DESCRIPTION

bric_clean_tmp will delete files from the tmp directories used by Bricolage
which are over a 12 hours old. This will prevent Bricolage from filling up your
hard drive with stale lockfiles and other viscera.

=head1 AUTHOR

Sam Tregar <stregar@about-inc.com>

=cut

use File::Spec::Functions qw(catdir);

BEGIN {
    # $BRICOLAGE_ROOT defaults to /usr/local/share/bricolage
    $ENV{BRICOLAGE_ROOT} ||= "/usr/local/share/bricolage";

    # use $BRICOLAGE_ROOT/lib if exists
    my $lib = catdir($ENV{BRICOLAGE_ROOT}, "lib");
    if (-e $lib) {
        $ENV{PERL5LIB} = defined $ENV{PERL5LIB} ?
          "$ENV{PERL5LIB}:$lib" : $lib;
        unshift @INC, $lib;
    }

    # make sure Bric is found
    eval { require Bric };
    die <<"END" if $@;
######################################################################

   Cannot load Bricolage libraries. Please set the environment
   variable BRICOLAGE_ROOT to the location of your Bricolage
   installation or set the environment variable PERL5LIB to the
   directory where Bricolage's libraries are installed.

   The specific error encountered was as follows:

   $@

######################################################################
END
}

use Bric::Util::Trans::FS;
use Bric::Config qw(TEMP_DIR);
use File::Find qw(find);
use Getopt::Std;

# Get the version number.
use Bric; our $VERSION = Bric->VERSION;

our ($opt_s, $opt_h, $opt_v);
getopts('s:hv');

usage() if $opt_h;
version() if $opt_v;

# Get the cutoff epoch.
$opt_s ||= 12 * 60 * 60;
my $cutoff = time - $opt_s;

# find and delete old files
find(sub {         
	 if (-f and (stat(_))[8] < $cutoff) {
	     unlink($_) or die "Unable to delete $File::Find::name: $!";
	 }
     },
     Bric::Util::Trans::FS->cat_dir(TEMP_DIR, "bricolage/lock"),
     Bric::Util::Trans::FS->cat_dir(TEMP_DIR, "bricolage/session")
    );

sub usage {
    my $prog = Bric::Util::Trans::FS->base_name($0);
    print qq{
Usage: $prog [opts]

Supported Options:
  -s Number of seconds since last file access that must be exceeded before
     deleting a file. Defaults to 43200 (12 hours). Note that this value should
     be less than the interval at which $prog is run. If $prog is run every 24
     hours (86400 seconds), the -s argument should be less than 86400.
     Otherwise, no files will ever be deleted, because $prog itself accesses
     each file.
  -h Print this usage statement.
  -v Print the version number.

};
}

sub version {
    print "\nBricolage Temp File Cleaner version $VERSION\n";
    usage();
}
