#!/usr/bin/perl
#
# compact -- compact your already-expired MV session database
#
# Bugs: uses only the default session lock and file names
# 

$USAGE = <<EOF;
usage: compact.pl [catalog-directory]

Set to your software and catalog directory
or pass it a directory name
EOF

my $Catdir = shift || die "$USAGE\n";

# I usually do
use strict;

my $type;     # GDBM_File or DB_File
my $flags;    # How to open file
my $ext;      # File extension

# Uncomment for Berkeley
BEGIN {
  DBCHECK: {
	eval {
		die if $ENV{MINIVEND_DBFILE};
		require GDBM_File;
		import GDBM_File;
		$type  = 'GDBM_File';
		$flags = &GDBM_WRCREAT;
		$ext   = '.gdbm';
	};

	last DBCHECK			unless $@;
	
	eval {
		require DB_File;
		import DB_File;
		$type  = 'DB_File';
		$flags = &O_RDWR | &O_CREAT;
		$ext   = '.db';
	};

	last DBCHECK			unless $@;

	die "You don't need this script, not GDBM_File or DB_File.\n";

  }
}

use Fcntl qw/:flock/;

my %session1;
my %session2;
my ($k, $v);

my $file1 = "$Catdir/session$ext";
my $file2 = "$Catdir/new_session$ext";

open(LOCK, "+<$Catdir/etc/session.lock")
    or open(LOCK, ">>$Catdir/etc/session.lock")
                            or die "open lockfile: $!\n";

flock(LOCK, LOCK_EX)
        or die "lock: $!\n";

tie(%session1, $type, $file1, $flags, 0777)
                            or die "tie $file1: $!\n";

unlink "$Catdir/new_session$ext";

tie(%session2, $type, $file2, $flags, 0777)
                            or die "tie $file2: $!\n";

while( ($k, $v) = each %session1) {
    $session2{$k} = $v;
}

untie %session1             or die "untie: $!\n";
untie %session2             or die "untie: $!\n";

rename $file2, $file1       or die "rename $file1 to $file2: $!\n";

