#!/usr/local/bin/perl -w

=head1 NAME

updateindex.pl - a script for creation of new database. 

=head1 SYNOPSIS

updateind.pl [B<-i> I<indexfile>]


=head1 DESCRIPTION

Upadets metainformation in the B<chgk> databse. Uses file
    L<./index> unless [B<-i>] option is used

An example of the index file follows:


=head1 BUGS

The database, user and password are hardcoded. 

=head1 SEE ALSO

createindex.pl(1)

=head1 AUTHOR

Boris Veytsman

=head1 $Id: updateindex.pl,v 1.2 2000/10/18 21:50:48 boris Exp $

=cut

    use strict;
use vars qw($opt_i $opt_h);

use Getopt::Std;
use DBI;

MAIN: 
{
    my $USAGE="Usage: updateindex.pl -i indexfile\n";
    getopts('hm:') or die $USAGE;
    if ($opt_h) {
	print $USAGE;
	exit 0;
    }
    my($source) = $opt_i || 'index';
    my($depth, @depthId);
    my $filename;
    my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "") 
	or die "Can't connect to DB chgk\n";

    open INFD, $source or die "Can't open input file: $!\n";
    while (<INFD>) {
	chomp;
	s///;
	next if (/^\s*$/);
	if (s/^(\w*)//) { # File found
	    $filename = $1;
	    $depth = -1;
	} else {  # Group found
	    undef $filename;
	    $depth = -2;
	}
	s/^(\t*)//;
	$depth += length($1);
	if ($depth < 0) {
	    die "Wrong line $_\n";
	}
	s/^\s*//;
	s/\s$//;
	my $title = $dbh->quote($_);
	my $ParentId = ($depth) ? $depthId[$depth - 1] : 0;
	my $sth;
	my $type;
	if (defined $filename) {
	    $type=$dbh->quote('ş');
	    $filename = $dbh->quote($filename);
	    $sth = $dbh->prepare("SELECT Id FROM Tournaments 
                                  WHERE FileName=$filename");
	    $sth->execute;
	    if ($sth->fetchrow) {
		print "$filename is already in the DB!\n";
		next;
	    }
	    $sth = $dbh->prepare("INSERT INTO Tournaments
			(Title, ParentId, FileName, Type) 
			VALUES ($title, $ParentId, $filename, $type;)");
	    $sth->execute;
	} else {
	    $sth->execute;
	    $sth = $dbh->prepare("SELECT Id FROM Tournaments 
                                  WHERE Title=$title");
	    $type=$dbh->quote('ç');
	    if ($sth->fetchrow) {
		print "$title is already in the DB!\n";
		next;
	    }
	    $sth = $dbh->prepare("INSERT INTO Tournaments
			(Title, ParentId,  Type) 
			VALUES ($title, $ParentId, $type;)");
	    $sth->execute;
	    my $Id = $sth->{'mysql_insertid'};
	    $depthId[$depth] = $Id;
	}

    }
    $dbh->disconnect;
}
