#!/usr/bin/perl -s

require "MBGD_Conf.pl";
require "libMBGDaxes.pl";
require "MBGD_commonUpdate.pl";
use File::Basename qw{basename};

if (! @ARGV) {
	die "Usage: $0 upd_species ....\n" ;
}

$curr_tmp = MBGD::DB->new($UPD_dbiCurrTmp);
$work_tmp = MBGD::DB->new($UPD_dbiTmp);

foreach $sp (@ARGV) {
	$where .= " or " if ($where);
	$where .= " spec like '%$sp%'"
}
$where = " not ($where)" if ($where);
if ($cdate) {
	$where .= " and " if ($where);
	$where .= " cdate >= $cdate";
}

$out = $curr_tmp->select_fetch('cluster_tables', {field=>'tabid', where=>$where});
foreach $o (@{$out->{INFO}}) {
	push(@tabids, $o->{tabid});
}

foreach $f (<$UPD_dirMysqlTmpDb/{cluster,clusttab,clusttree}_default*>) {
	$bname = basename($f);
	$bname =~ s/default/prev/;
   	system("cp $f $UPD_dirMysqlTmpDbWork/$bname");
}
$sth = $curr_tmp->execute("select * from $UPD_dbnameCurrTmp.cluster_tables where tabid='default'");
$res = $sth->fetchrow_hashref();
foreach $fld (keys %{$res}) {
	push(@fields,$fld);
	if ($fld eq 'tabid') {
		$val = 'prev';
	} else {
		$val = $res->{$fld};
	}
	push(@values,$val);
}
$sql = "insert into cluster_tables " .
	"(" . join(",",@fields) . ") values(?,?,?,?)";
$sth = $work_tmp->prepare($sql);
$sth->execute(@values);

foreach $p (@tabids) {
	print "$UPD_dirMysqlTmpDb/cluster_$p", $UPD_dirMysqlTmpDbWork, "\n";
next if ($TEST);

	if ($p =~ /^\d+/) {
	   system("cp $UPD_dirMysqlTmpDb/cluster_${p}* $UPD_dirMysqlTmpDbWork");
	   system("cp $UPD_dirMysqlTmpDb/clusttab_${p}* $UPD_dirMysqlTmpDbWork");
	   system("cp $UPD_dirMysqlTmpDb/clusttree_${p}* $UPD_dirMysqlTmpDbWork");
	   $work_tmp->execute("insert into cluster_tables " .
		"select * from $UPD_dbnameCurrTmp.cluster_tables where tabid='$p'");
	}
}
