89d40a773da7974f7cd862738a2ea2097cd56c93
[www.energie.vellum.cz.git] / obsah_init.pl
1 #! /usr/bin/perl
2 #
3 #       $Id$
4
5 use strict;
6 use DBI;
7
8 use vars qw/$db_driver $db_host $db_user $db_pwd $DB_PWD $db_name $db/;
9 use vars qw/$tb_obsah/;
10
11 $db_driver="mysql";
12 $db_host="";
13 $db_user="short";
14 $DB_PWD=$ENV{"HOME"}."/priv/mysql.${db_user}.pwd";
15 $db_name="short";
16 $tb_obsah="energie_obsah";
17
18 open DB_PWD or die "Failed open \"$DB_PWD\": $!";
19 $db_pwd=<DB_PWD>;
20 chomp $db_pwd;
21 close DB_PWD;
22
23 $db=DBI->connect("DBI:$db_driver:database=$db_name;host=$db_host",$db_user,$db_pwd) or die "Database open fail: $!";
24
25 sub db_do
26 {
27 my( $cmd )=@_;
28
29         $db->do($cmd) or die("SQL command \"$cmd\" failed: $!");
30 }
31
32 eval { &db_do("drop table $tb_obsah") };
33
34 &db_do("create table $tb_obsah ("
35                 ."year year(4) not null,"
36                 ."month tinyint not null,"
37                 ."month_last tinyint not null,"
38                 ."contents text not null"
39                 .")");
40
41 &db_do("alter table $tb_obsah add unique (year,month)");
42
43
44 use vars qw/$insert_tb_obsah $year $month $month_last $contents/;
45
46 sub where
47 {
48         return " in file $ARGV on line $.";
49 }
50
51 sub flush_month
52 {
53         $_=$contents;
54         return if !defined $_;
55         if (!$_) {
56                 print("Empty contents".&where()."!\n");
57                 }
58         else {
59                 tr/ \t\n/  \n/s;
60                 s/([\001\n]) | ([\002\n])/$1$2/g;
61                 s/\nstrana \.\.\. ([\d ,]+\002)/\003$1/g;
62                 die "Page marker not found somewhere in this month".&where() if (/\001[^\003]*\002/);
63                 tr/\002//d;
64                 $_=substr($_,1);
65                 }
66         $insert_tb_obsah->execute($year,$month,$month_last,$_) or die "SQL insert failure: $!";
67         undef $year,$month;
68         undef $contents;
69 }
70
71 $insert_tb_obsah=$db->prepare("insert into $tb_obsah (year,month,month_last,contents) values (?,?,?,?)")
72                 or die "Prepare fail: $!";
73
74 while (<>) {
75         chomp;
76         if (m#^EaP (\d+)(-(\d+))?/(\d+)$#) {
77                 &flush_month();
78                 $month=$1;
79                 $month_last=($3 ? $3 : $1);
80                 $year =$4;
81                 $contents="";
82                 next;
83                 }
84         if (/^\.\s(.*)$/) {
85                 $contents.="\001$1\002";
86                 next;
87                 }
88         if (/^\s(.*)$/) {
89                 $contents=substr($contents,0,-1)."\n$1\002";
90                 next;
91                 }
92         die "Unexpected text".&where().": $_" if (/\S/);
93         }
94 &flush_month();
95
96 print("success.\n");