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