#!/usr/bin/perl
# Written by Ron Johnson
# Copyright (C) 19 Jan 2007
# GPL licensed.

# This program cleans up the /tmp directory by moving things into
# a subdirectory of /tmp.

# The name of this program, as it will be displayed in any messages:
$prog="tmpcleanup";

# Create a string in the format 'YYYY-MM-DD@HH.MM.SS'
$NOW=`/bin/date +%F@%H.%M.%S`; chomp($NOW);

# Our directory names will begin with the prefix...
$PREFIX="tmp-cleanup";

# This is the actual directory name we'll try to move things to.
$movename="${PREFIX}-$NOW";

# And this is the full path of $movename.
$moveto="/tmp/$movename";

# Get a list of files in the tmp dir first (before we make our dir)
# Note the trailing slash is important, in case /tmp is a symlink.
opendir(D,"/tmp/");
@files=readdir(D);
closedir(D);

# If we can't create the dir, just die.
unless ( mkdir($moveto,0) )
	{die "${prog}: Unable to create 'moveto' dir, $moveto\n";}

# If we can't ensure the permissions are correct, just die.
unless ( chmod(01777,$moveto) )
	{die "${prog}: Unable to set proper permissions for $moveto\n";}

$moved=0;
foreach(@files)
	{
	$f="/tmp/$_";		# Full path/file to be moved
	$t="$moveto/$_";	# Full path/file to move it to
	next if /^\.\.?$/;	# Skip . and .. pseudo dirs
	next if /^$PREFIX/;	# Skip previous saves that we made.

	# Finally, actually move the file, increment $moved if successful.
	$moved++ if rename($f,$t);
	}

# Say how much we moved if we moved anything, otherwise, remove the
# dir we made so we aren't adding to the /tmp clutter.
if ($moved>0)
	{print "${prog}: Moved $moved files to $moveto\n";}
else
	{unlink($moveto);}
