#!/usr/bin/perl


use strict;
use warnings;
use lib '/home/httpd/lib/perl';
use GDBM_File;
use File::Find;
use LONCAPA;
use LONCAPA::Configuration;
use Cwd;

my $dump_db = '/home/httpd/perl/debug/dump_db_static_32';
my $create_db = '/home/httpd/perl/debug/create_db_dynamic';
if (!-x $dump_db || !-x $create_db) {
    print("Unable to run needed helper programs\n $dump_db\n $create_db\n.");
    exit(-1);
}

my  %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};

{
    my $straight;
    sub lock_db {
	my ($fname) = @_;
	my $dbref;
	$fname = &Cwd::abs_path($fname);
	if ($fname =~ m/^\Q$perlvar{'lonUsersDir'}\E/) {
	    $dbref=&LONCAPA::locking_hash_tie($fname,&GDBM_READER());
	    $straight=0;
	} else {
	    if (tie(my %db,'GDBM_File',$fname,&GDBM_READER(),0640)) {
		$dbref = \%db;
	    }
	    $straight=1;
	}
	return $dbref;
    }

    sub unlock_db {
	my ($dbref) = @_;
	if ($straight) {
	    untie($dbref);
	} else {
	    &LONCAPA::locking_hash_untie($dbref);
	}
    }
}

sub process_db {
    return if ($_!~m/\.db$/);
    my $file = $_;
    my $dbref =&lock_db($file);
    print("attempting $file\n");
    my %newdb;
    my $new_file = $file.'.new';
    system("$dump_db -f $file|$create_db -f $new_file");
#    print("finishing $dbref\n");
    untie($dbref);
    system("/bin/mv $file $file.old");
    system("/bin/mv $file.new $file");
    &unlock_db($dbref);
}

sub main {
    find(
	 {
	     no_chdir   => 1,
	     wanted     => \&process_db,
	 }, 
	 $perlvar{'lonUsersDir'}
	 );
}

&main();
