#! /tools/bin/perl  -w

use DBI;
use strict;
use vars qw ($dbh $sth);
require '/usr/www/push/sqlcommon20.pl';
require '/usr/www/push/common20.pl';
#require '/usr/www/push/getrev20.pl';
my $dbh=&ConnectToDatabase("push20");
my $root_cvs="/usr/www/push/temp/";
my $root_stage;
if (-e "/usr/www/push/qa_branch/src/Makefile") {
	$root_stage="/usr/www/push/qa_branch/";
} else {
	$root_stage="/usr/www/push/prod_branch/";
} # End of if
my $root_www="/usr/www/push/prod_branch/";
my $dirlist="/usr/www/push/scripts/dirlist30_pushtool";
my $dir;

open(FILE,$dirlist);
my @dirs=<FILE>;
close(FILE);
foreach $dir (@dirs){
	chomp $dir;
	print "$dir\n";
	&get_all_versions($root_cvs,$dir,"cvs");
	&get_all_versions($root_stage,$dir,"stage");
	&get_all_versions($root_www,$dir,"www");
} # End of foreach

sub ConnectToDatabase {
    my $database = shift ;
    my ($dsn)="DBI:mysql:$database:keefer.epinions.com";
 DBI->trace(1, "/usr/www/push/var/allload30.out");
        $dbh = DBI->connect($dsn, "root", "push")
            || die "$DBI::errstr - Can't connect to database server: .";
} # End of ConnectToDatabase

sub get_all_versions
{
my $root=shift;
my $path=shift;
my $area=shift;
my $m;
my @buf;
my $full_path = $root . $path . "/CVS/Entries";
$full_path =~  s/\/\//\//g; # get rid of // from path
print "FULL-PATH-$full_path\n";
#return if !(-e $full_path);
open(STAT,"$full_path");
@buf=<STAT>;
close(STAT);

foreach $m (@buf) {
        next if ($m =~ m/^D/);
        chomp ($m);
        my ($g,$filename,$version,$rest)=split (/\//,$m,4);
	my $filepath=$path."/$filename";
	print "$filepath\n";
	print "$version\n";
	print "FILE-$filename DIR-$path\n";
	&getrev($area,$filename,$path,$version,$dbh);
} # End of foreach
} # End of get_all_versions

sub choke
{
my $reason=shift;
print "Failing because: $reason !!!!\n";
exit 1;
} # End of choke

sub getrev
{
my $area=shift;
my $file=shift;
my $dir=shift;
my $revision=shift;
my $dbh=shift;
my $full_path=$dir."/$file";
my $sth;

print "Updating $file in the directory $dir in the area $area...\n";
my $query = " select id from filepaths where path=\'${full_path}\' ";
$sth= $dbh->prepare(qq {$query} ) || &choke($sth->errstr);
$sth->execute() || &choke ($sth->errstr);
my ($fileid) = $sth->fetchrow_array();
#my $revision=&getfile($full_path,$temp_dir);
if (! $fileid) {
	print "File needs to be added...";
	my $insert="insert into filepaths values (NULL,'$full_path','$revision',NULL,NULL,NULL,NULL)";
	print "INSERT-$insert\n";
	$sth= $dbh->prepare(qq{ $insert } ) || &choke($sth->errstr);
	$sth->execute() || &choke ($sth->errstr);
	$sth->finish(); #cleanup
} else {
	print "File needs to be updated...";
	&update_db_version($dbh,$fileid,$revision,$area);
} # End of if

} # End of getrev

