#!/usr/bin/perl
#
# dbchk.pl: external db file management for MU*
#
# Designed to be called by cron and make
# a backup of the db tagged with the date.
# Any given backup will be held for 7 days
# before being deleted by this program.
#
# UNTESTED! PLEASE REPORT BUGS TO alansz@mellers1.psych.berkeley.edu
#
# usage: dbchk [-d<data directory>] [-s<save directory>] [-f<filename>]
#
# By Michael Baker (Inigo, mbaker@cp.tybrin.com, 
# Modified by Chris Hardy (Westley), modified slightly by Alan Schwartz


# Set usage for use in error messages.
$usage = "dbchk [-d<data directory>] [-s<save directory>] [-f<filename>]\n";

# require/include the getopts.pl program
# to handle switch <-x> type arguments.
require 'getopts.pl';

# Set default variables for db location
$directory = "~/game/data";
$savedir = "~/game/save";
$filename = "minimal.db.Z";

# Call Getopts (included earlier) to handle -d and -f switches
# the ':' following indicates that data follows the switch.
# Then process the data via if's.
&Getopts('d:f:s:') || die "$usage";

if ($opt_d) { $directory = $opt_d; }
if ($opt_f) { $filename = $opt_f; }
if ($opt_s) { $savedir = $opt_s; }

# Get the current time to stamp the backup with.
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time());
$filestamp = join("",$mon,$mday,$year);

# Make the backup of the db
system("cp $directory/$filename $savedir/$filename.$filestamp");

# This section removes the saves over 7 days old.
opendir(DATED,$savedir) || die "Unable to remove old backups.\n";
@files = readdir(DATED);
closedir(DATED);
@files = grep(/$filename\./,@files);

while (shift(@files)) {
	if (-M > 7) {
		unlink($_) || warn "Unable to remove $_!\n";
	}
}
exit 0;
