package KITTENWEB::BULKDATA;

@alltags = ("page", "link", "refs");

# external 
sub makebackup { # db
    my($db) = @_;
    local (*TMPF);
    my ($out,@names,$bdir,@tm,$tm,%ndb,%tag);
    @tm = localtime();
    $tm = sprintf("%02d%02d%02d",$tm[5],$tm[4]+1,$tm[3]);
    $bdir=$db.".backup.".$tm;
    mkdir($bdir,0777);
    foreach $tag (@alltags) {
	tie %ndb, STASH, $db, $tag;
	foreach (keys %ndb) {
	    open(TMPF,">$bdir/$tag:$_");
	    print TMPF $ndb{$_};
	    close(TMPF);
	}
	untie %ndb;
    }
    &HTML::print_status_page("backup complete");
}

# external
sub loadbackup { #db, dir
    my($db, $dir) = @_;
    local *TMPF;
    my ($contents,$/,@keys,@refs,$cnt,$k,$record);
    my (%ndb,%tag);
    print "recover $db from $dir\n";
    $/ = undef;
    foreach $tag (@alltags) {
	tie %ndb, STASH, $db, $tag;
	while(<$dir/$tag:*>) {
	    open(TMPF,"<$_");
	    $_ =~ s#$dir/##;
	    print $_,"\n";
	    $record = <TMPF>;	# makes sure context is correct
	    $ndb{$_}=$record;
	    close(TMPF);
	    $cnt++;
	}
	untie %ndb;
    }
    print "recovered $cnt records\n";
    $cnt = 0;
    # now rebuild invrefs
    &rebuild_invrefs($db);
}

# external
sub rebuild_invrefs { # database
    my($db) = @_;
    my (@keys,$k,@refs,@tmp,$cnt,%pdb);
    tie %pdb, STASH, $db, "page";
    @keys = keys %pdb;

    foreach $k (@keys) {
	@refs = &KITTENWEB::RENDER::getrefs($pdb{$k});
	foreach (@refs) {
	    tie %idb, STASHREFS, $db, $_;
	    $idb{$k} = 1;
	    untie %idb;
	    $cnt++;
	}
    }
    untie %pdb;
    print "recovered $cnt inv refs\n";
}

1;
