#!/usr/bin/perl

use strict;
use JSON;
use DBI;
use warnings;

my $conf = load_conf("../etc/autodoc.json");
my $dbh  = sqlconnect($conf->{sql});

my @del = (
	'pages',
	'documents',
	'tags',
	'words'
);

foreach ( @del ) {
	print "DELETE FROM $_\n";
	sqlquery($dbh, "DELETE FROM $_");
}

my $q = sqlquery($dbh, "SHOW TABLE STATUS");
while(my $h = $q->fetchrow_hashref()) {
	print "="x80 . "\n";
	foreach my $name ( sort keys %{$h} ) {
		next if $name !~ /^(Name|Rows)$/;
		printf("%10s: %s\n",
			$name,
			defined $h->{$name} ? $h->{$name} : 'NULL'
		);
	}
}


sub load_conf {
	my($file) = @_;

	my $x='';

	open(F,"$file") || fatal_api_error(500,"Failed to load configuration file");
	while(<F>) { $x.=$_; }
	close(F);

	return from_json($x);
}

sub sqlconnect {
	my($sql) = @_;

	my $dsn = "DBI:mysql:database=$sql->{base};host=$sql->{host}";
	my $dbh = DBI->connect($dsn, $sql->{user}, $sql->{pass}) || \\
		print STDERR "Failed to connect to database\n";

	return $dbh;
}

sub sqlquery {
	my $dbh   = shift;
	my $query = shift;
	my @args  = @_;

	my $sth = $dbh->prepare($query) || print STDERR $dbh->error();
	$sth->execute(@args) || print STDERR $sth->error();
	return $sth;
}
