#! /tools/bin/perl  -w

use DBI;
use strict;
use vars qw ($dbh $dest);
require '/usr/www/push/sqlcommon20.pl';
require '/usr/www/push/common20.pl';
my $dbh=&ConnectToDatabase("push20");
my $dirlist="/usr/www/push/scripts/dirlist30";
my $location=shift;
if (($location ne "qa_branch") and ($location ne "prod_branch")) {
	print "Location not defined correctly (qa_branch prod_branch)!!!!\n";
	exit 1;
} # End of if
my $root="/usr/www/push/$location/";
my $dir;
my $dest;
if ($location eq "qa_branch") {
	$dest="stage";
} elsif ($location eq "prod_branch") {
	$dest="www";
} # End of if

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

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

sub get_all_versions
{
my $path=shift ;
my $m;
my @buf;
my $full_path = $root . $path . "/CVS/Entries";
$full_path =~  s/\/\//\//g; # get rid of // from path
#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 "FILE-$filepath VER-$version\n";
	&update_db($dbh,$filepath,$version);
} # End of foreach
} # End of get_all_versions

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

sub update_db
{
my $dbh=shift;
my $filepath=shift;
my $version=shift;
my $type;
my $sth;

my $query="select id from filepaths where path='$filepath'";
print "QUERY-$query\n";
$sth= $dbh->prepare(qq{ $query } ) || &choke_it($sth->errstr);
$sth->execute() || &choke_it ($sth->errstr);
my ($fileid) = $sth->fetchrow_array();
if ($sth->rows) {
	my $update="update filepaths set $dest"."version='$version' where id='$fileid'";
	print "UPDATE-$update\n";
	$sth= $dbh->prepare(qq{ $update } ) || &choke_it($sth->errstr);
#	$sth->execute() || &choke_it ($sth->errstr);
	$sth->finish(); #cleanup
} else {
	my $insert="insert into filepaths values (NULL,'$filepath','$version',NULL,NULL,NULL,NULL)";
	print "INSERT-$insert\n";
	$sth= $dbh->prepare(qq{ $insert } ) || &choke_it($sth->errstr);
#	$sth->execute() || &choke_it ($sth->errstr);
	$sth->finish(); #cleanup
} # End of if
} # End of update_db
