#!/bin/sh
#
# License: Copyright 2015 SpinetiX. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
#
# Copyright 1999-2003 MontaVista Software, Inc.
# Copyright 2002, 2003, 2004 Sony Corporation
# Copyright 2002, 2003, 2004 Matsushita Electric Industrial Co., Ltd.
#

# NOTE: this is a bit harsh but we clean files based on modification
# time (mtime) instead of access time (atime) since we run filesystems
# with the noatime option

# Maximum number of days to keep a file, note that since fractional
# parts are ignored 1 will keep a file for just under 2 days (0 is allowed)
MAXDAYS=0

# The root of raperca directories (no spaces allowed)
SRVDIR=/srv/raperca

# The directories to check (no spaces allowed in dir names)
DIRS="$SRVDIR/capture"

# First remove files, in as few calls to rm as possible to avoid
# a fork bomb in case many files are present
find $DIRS -xdev -mindepth 1 \
    -mtime +"$MAXDAYS" \
    -type f \
    -print0 | xargs -0r rm -f --

# Now remove empty directories that also satisfy the time constraint
# (note that there is a cascading effect in directory removal as
# removing a file or subdir from a dir changes its modification time
# and thus will only become eligible after the time constraint expires
# again, but this is OK as directories are not big themselves)
find $DIRS -xdev -mindepth 1 \
    -mtime +"$MAXDAYS" \
    -type d \
    -empty \
    -depth -exec rmdir -- {} \;

exit 0
