#!/usr/bin/perl
# This performs the same database corruption tests done in mythtv/libs/libmythtv/dbcheck.cpp
# during the upgrade to 0.22.
use DBI;
use DBD::mysql;
use Getopt::Long;

($host, $database, $user, $password, $help) = ('localhost', 'mythconverg', 'mythtv', 'mythtv');
GetOptions (    "host|h=s" => \$host,
		"database|d=s" => \$database,
		"user|u=s" => \$user,
		"password|p=s" => \$password,
                "help|?" => \$help)
|| &syntax(-1);
&syntax(0) if ($help);
sub syntax {
	my ($estat) = @_;
	print <<SYN
Syntax: dbtest.pl [options]

Options:
	--help, -?: Help.
	--host, -h: Host name.  Default: localhost
	--database, -d: Database name. Default: mythconverg
	--user, -u: User name.  Default: mythtv
	--password, -p: Password.  Default: mythtv
SYN
;
	exit($estat);
}

$dsn = "DBI:mysql:database=$database;host=$host";
$dbh = DBI->connect($dsn, $user, $password);

die "Can't connect to the database using specified options!\n" if (!$dbh);

%tables = (
	'people'=>[['name'], 'name(41)'],
	'oldprogram'=>[['oldtitle'], 'oldtitle'],
	'oldrecorded'=>[['title', 'subtitle', 'description'], 'station, starttime, title'],
	'recorded'=>[['title', 'subtitle', 'description'], undef]
);

$fail = 0;
foreach $tablename (keys %tables) {
	print "Testing $tablename...\n";
	$data = $tables{$tablename};
	$convcolp = @$data->[0];
	$index = $$data[1];
	$csql = "CREATE TEMPORARY TABLE temp_$tablename SELECT * FROM $tablename";
	$asql = "ALTER TABLE temp_$tablename";
	$first = 1;
	foreach $col (@$convcolp) {
		$asql .= ',' if (!$first);
		$first = 0;
		$asql .= ($col eq 'description') ?
			" MODIFY $col BLOB NOT NULL" :
			" MODIFY $col VARBINARY(255) NOT NULL default ''";
	}
	($rv = $dbh->do($csql)) || die "Can't create temp_$tablename table: $csql\n";
	($rv = $dbh->do($asql)) || die "Can't alter temp_$tablename table: $asql\n";
	die "Unable to get current warnings!\n"
		if (!(@row = $dbh->selectrow_array("SHOW COUNT(*) WARNINGS")) or scalar(@row) < 1);
	if ($row[0]) {
		print "Corruption detected altering table temp_$tablename, Warnings: ${row[0]}\n";
		$fail++;
	} else {
		if ($index) {
			$isql = "ALTER TABLE temp_$tablename ADD UNIQUE INDEX verify_unique ($index)";
			if (!($dbh->do($isql))) {
				print "Corruption detected creating unique index on temp_$tablename ($index)\n";
				$fail++;
			}
		}
	}
	($rv = $dbh->do("DROP TABLE temp_$tablename")) || die "Can't drop temp_$tablename table\n";
}

if ($fail) {
	print "Failures detected on $fail tables\n";
} else {
	print "No failures detected\n";
}
