#! /usr/bin/perl
#
#	$Id$

use strict;
use DBI;

use vars qw/$db_driver $db_host $db_user $db_pwd $DB_PWD $db_name $db/;
use vars qw/$tb_obsah/;

$db_driver="mysql";
$db_host="";
$db_user="short";
$DB_PWD=$ENV{"HOME"}."/priv/mysql.${db_user}.pwd";
$db_name="short";
$tb_obsah="energie_obsah";

open DB_PWD or die "Failed open \"$DB_PWD\": $!";
$db_pwd=<DB_PWD>;
chomp $db_pwd;
close DB_PWD;

$db=DBI->connect("DBI:$db_driver:database=$db_name;host=$db_host",$db_user,$db_pwd) or die "Database open fail: $!";

sub db_do
{
my( $cmd )=@_;

	$db->do($cmd) or die("SQL command \"$cmd\" failed: $!");
}

eval { &db_do("drop table $tb_obsah") };

&db_do("create table $tb_obsah ("
		."year year(4) not null,"
		."month tinyint not null,"
		."month_last tinyint not null,"
		."sequential smallint not null,"
		."contents text not null"
		.")");

&db_do("alter table $tb_obsah add unique (year,month)");


use vars qw/$insert_tb_obsah $year $month $month_last $sequential $contents $first/;

sub where
{
	return " in file $ARGV on line $.";
}

sub flush_month
{
	$_=$contents;
	return if !defined $_;
	if (!$_) {
		print("Empty contents".&where()."!\n");
		}
	else {
		tr/ \t\n/  \n/s;
		s/([\001\n]) | ([\002\n])/$1$2/g;
		die "Page marker not found somewhere in this month".&where() if (/^[^\004]*\001[^\003\004]*\002/);
		die "Duplicate page markers in this month".&where() if (/strana /);
		tr/\002//d;
		$_=substr($_,1);
		}
	$insert_tb_obsah->execute($year,$month,$month_last,$sequential,$_) or die "SQL insert failure: $!";
	undef $year,$month;
	undef $contents;
	undef $first;
}

$insert_tb_obsah=$db->prepare("insert into $tb_obsah (year,month,month_last,sequential,contents) values (?,?,?,?,?)")
		or die "Prepare fail: $!";

while (<>) {
	chomp;
	if (m#^EaP (\d+)(-(\d+))?/(\d+) \((\d+)(-\d+)?\)$#) {
		&flush_month();
		$month=$1;
		$month_last=($3 ? $3 : $1);
		$year =$4;
		$sequential=$5;
		$contents="";
		next;
		}
	if (/^Příloha:$/) {
		die "Multiple \"Příloha\"s".&where() if ($contents=~/\004/);
		$contents.="\004";
		next;
		}
	if (/^[^ \t]/ || (/^\s/ && $contents=~/\004/)) {
		$contents.="\001$_\002";
		$first=$_;
		next;
		}
	if (/^\s+strana \.\.\. ([\d ,-]+)$/) {
		die "Page number without start".&where() if ("\002"!=substr($contents,-1,1));
		die "Page number already specified".&where() if ($contents=~/\003[^\001\002\004]*\002$/);
		$contents=substr($contents,0,-1)."\003$1\002";
		next;
		}
	if (/^\s(.*)$/) {
		my( $s )=$1;
		die "INTERNAL: continuation for \"Příloha\"".&where() if ($contents=~/\004/);
		die "Continuation contents without start".&where() if ("\002"!=substr($contents,-1,1));
		if ($contents=~/\003[^\001\002\004]*\002$/) {
			die "First line not found".&where() if !defined($first);
			$contents.="\001$first\002";
			}
		$contents=substr($contents,0,-1)."\n$s\002";
		next;
		}
	die "Unexpected text".&where().": $_" if (/\S/);
	}
&flush_month();

print("success.\n");
