config.php introduced
[www.energie.vellum.cz.git] / obsah_init.pl
diff --git a/obsah_init.pl b/obsah_init.pl
new file mode 100755 (executable)
index 0000000..a5fef69
--- /dev/null
@@ -0,0 +1,89 @@
+#! /usr/bin/perl
+
+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,"
+               ."contents text not null"
+               .")");
+
+&db_do("alter table $tb_obsah add unique (year,month)");
+
+
+use vars qw/$insert_tb_obsah $year $month $month_last $contents/;
+
+sub where
+{
+       return " in file $ARGV on line $.";
+}
+
+sub flush_month
+{
+       $_=$contents;
+       return if !defined $_;
+       die "Empty contents".&where() if !$_;
+       tr/ \t\n/  \n/s;
+       s/([\001\n]) | ([\002\n])/$1$2/g;
+       s/\nstrana \.\.\. ([\d ,]+\002)/\003$1/g;
+       die "Page marker not found somewhere in this month".&where() if (/\001[^\003]*\002/);
+       tr/\002//d;
+       $insert_tb_obsah->execute($year,$month,$month_last,substr($_,1)) or die "SQL insert failure: $!";
+       undef $year,$month;
+       undef $contents;
+}
+
+$insert_tb_obsah=$db->prepare("insert into $tb_obsah (year,month,month_last,contents) values (?,?,?,?)")
+               or die "Prepare fail: $!";
+
+while (<>) {
+       chomp;
+       if (m#^EaP (\d+)(-(\d+))?/(\d+)$#) {
+               &flush_month();
+               $month=$1;
+               $month_last=($3 ? $3 : $1);
+               $year =$4;
+               $contents="";
+               next;
+               }
+       if (/^\.\s(.*)$/) {
+               $contents.="\001$1\002";
+               next;
+               }
+       if (/^\s(.*)$/) {
+               $contents=substr($contents,0,-1)."\n$1\002";
+               next;
+               }
+       die "Unexpected text".&where().": $_" if (/\S/);
+       }
+&flush_month();
+
+print("success.\n");