#!/usr/bin/perl -s

require "MBGD_Conf.pl";
require "libMBGDaxes.pl";
require "MBGD_commonUpdate.pl";
use MbgdUserGenomeCommon;

$DB = 'mbgd_tmp2' if (! $DB);

@tabids = @ARGV;

if ($zero) {
	my $cnt;
	if ($zero =~ /[1-9]\d+/) {
		$cnt = $zero;
	} else {
		$cnt = 0;
	}
	@tabnames = split(/\n/,`mysqlshow --status $DB 'clusttab_%' | awk -F'|' '\$6<=$cnt {print \$2}'`);
	foreach $n (@tabnames) {
		$n =~ s/\s*clusttab_//;
		if ($n) {
			push(@tabids, $n);
		}
	}
}

if (! @tabids && ! $all) {
	die "Usage: $0 tableid ....\n" ;
}

$DB = "dbi:mysql:$DB";

$tmpdb = MBGD::DB->new($DB);
#if ($print) {
#	foreach $tid(@tabids) {
#		print ">$tid<\n";
#	}
#	exit;
#}

if ($all) {
#	@tab = $tmpdb->list_tables;
	@tab = &list_tables($tmpdb);
	foreach $t (@tab) {
		($tabid) = ($t =~ /([a-z0-9]+)$/);
		if ($tabid) {
			next if ($all eq 'user' &&
				($tabid eq 'all' || $tabid eq 'default' || $tabid eq 'prev'));
			$TabIDs{$tabid} = 1;
		}
	}
	@tabids = keys %TabIDs;
}

foreach $p (@tabids) {
	print STDERR "$p\n";
	next if ($print);

    if ($p =~ /[^0-9A-Z]/i) {
        # $B1Q?t;z0J30$r4^$`%/%i%9%?!<%F!<%V%k$OB8:_$7$J$$!#(B
        # $B2?$+4V0c$C$F;XDj$5$l$F$$$k$H;W$o$l$k!#:o=|$7$J$$(B
        next;
    }

	$tmpdb->execute("drop table cluster_$p");
	$tmpdb->execute("drop table clusttab_$p");
	$tmpdb->execute("drop table clusttree_$p");
	if ($p =~ /^\d+$/) {
		$tmpdb->execute("delete from cluster_tables where tabid=$p");
	} else {
		$tmpdb->execute("delete from cluster_tables where tabid='$p'");
	}
    if (-e $ENV{'MBGD_TMP'}) {
        system("rm $ENV{'MBGD_TMP'}/*.$p");
    }
    else {
        system("rm $DIR_mbgdhome/MBGD.tmp/*.$p");
    }
}

sub list_tables {
	my($db) = @_;
	my($where);
	my(@out);
	if ($cdate =~ /^\d+/) {
		$where = " cdate < $cdate";
	}
	$where = "where $where" if ($where);
	$sth = $db->execute("select spec,tabid from cluster_tables $where");
	while (@a = $sth->fetchrow_array) {
		($spec,$tabid) = @a;
		push(@out, $tabid);
	}
	@out;
}
