#!/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=1

# The directories to check (no spaces allowed in dir names)
# NOTE: include trailing slash so that if dir is a symlink this
# initial symlink will be followed.
DIRS="/tmp/ /var/tmp/"

# The lost+found dir and quota.user, quota.group, aquota.user and
# aquota.group files should be left untouched if owned by root.

# 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 \
    ! \( -name quota.user -uid 0 \) \
    ! \( -name quota.group -uid 0 \) \
    ! \( -name aquota.user -uid 0 \) \
    ! \( -name aquota.group -uid 0 \) \
    -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).
# We make an exception of /var/tmp/uploader as that directory should
# always exist even if empty.
find $DIRS -xdev -mindepth 1 \
    -mtime +"$MAXDAYS" \
    -type d \
    -empty \
    ! \( -name lost+found -uid 0 \) \
    ! -path /var/tmp/uploader \
    -depth -exec rmdir -- {} \;

exit 0
