warning for DVDs with corrupt data
[BackupPC.git] / bin / BackupPC_burnArchiveCLI
1 #!/usr/bin/perl
2
3 use strict;
4 use lib "__INSTALLDIR__/lib";
5
6 use DBI;
7 use BackupPC::Lib;
8 use BackupPC::SearchLib;
9 use Time::HiRes qw/time/;
10 use POSIX qw/strftime/;
11 use Term::Menus;
12 use File::Which;
13 use File::Path;
14
15 use Data::Dumper;
16
17 my $debug = 0;
18 $|=1;
19
20 # don't check for user
21 my $bpc = BackupPC::Lib->new(undef, undef, 1) || die;
22 my %Conf = $bpc->Conf();
23 %BackupPC::SearchLib::Conf = %Conf;
24
25 my $conf_bin;
26
27 $conf_bin->{'cdrecord'} = $Conf{CDRecordBin} || die "Need CDRecordBin in config.pl\n";
28 my $cdr_opts = $Conf{CDRecordOpts} || die "Need CDRecordOpts in config.pl\n";
29 $conf_bin->{'eject'} = $Conf{ejectBin} || die "Need ejectBin in config.pl\n";
30 my $eject_opts = $Conf{ejectOpts} || die "Need ejectOpts in config.pl\n";
31 $conf_bin->{'mkisofs'} = $Conf{mkisofsBin} || die "Need mkisofsBin in config.pl\n";
32
33
34 my $bin;
35 foreach my $c (qw/cdrecord eject mkisofs/) {
36         $bin->{$c} = which($conf_bin->{$c}) || die "$0 needs $c ($conf_bin->{$c}), install it\n";
37 }
38
39 my $start_t = time();
40
41 my $t_fmt = '%Y-%m-%d %H:%M:%S';
42
43
44 my $dsn = $Conf{SearchDSN} || die "Need SearchDSN in config.pl\n";
45 my $user = $Conf{SearchUser} || '';
46
47 my $dbh = DBI->connect($dsn, $user, "", { RaiseError => 1, AutoCommit => 1 });
48
49 my $tar_dir = $Conf{InstallDir}.'/';
50 $tar_dir .= $Conf{GzipTempDir} || die "GzipTempDir isn't defined in configuration";
51
52 die "problem with $tar_dir, check GzipTempDir in configuration\n" unless (-d $tar_dir);
53
54 my $iso_dir = $Conf{InstallDir}.'/';
55 $iso_dir .= $Conf{ISOTempDir} || die "ISOTempDir isn't defined in configuration";
56 die "problem with $iso_dir, check ISOTempDir in configuration\n" unless (-d $iso_dir && -w $iso_dir);
57
58 #---- subs ----
59
60 sub fmt_time {
61         my $t = shift || return;
62         my $out = "";
63         my ($ss,$mm,$hh) = gmtime($t);
64         $out .= "${hh}h" if ($hh);
65         $out .= sprintf("%02d:%02d", $mm,$ss);
66         return $out;
67 }
68
69 sub curr_time {
70         return strftime($t_fmt,localtime());
71 }
72
73 sub dumpArchive2XML($$$)
74 {
75         my ($dbh, $dvd_nr, $filename) = @_;
76         my %archive;
77
78         my $output = new IO::File('> '.$filename.'.tmp');
79         my $writer = new XML::Writer(OUTPUT=>$output, NEWLINES => 1);
80
81         print "Dumping file list for DVD $dvd_nr, countdown:";
82
83         $writer->pi('xml-stylesheet', 'href="archive.css" type="text/css"');
84
85         my $files_sql = q{
86                 SELECT 
87                         files.path AS path,
88                         files.date AS date,
89                         files.type AS type,
90                         files.size AS size
91                 FROM files, backups, shares
92                 WHERE files.backupnum=backups.num AND
93                         files.shareid=shares.id AND
94                         shares.hostid=backups.hostid AND
95                         backups.id=?
96         };
97
98         my $backups_sql = q{
99                 SELECT
100                         backups.id   AS backup_id,
101                         hosts.name   AS host,
102                         backups.num  AS num,
103                         backups.date AS date,
104                         shares.name  AS share,
105                         backups.size AS backup_size,
106                         backups.inc_size AS compress_size
107                 FROM backups, archive_backup, hosts, shares
108                 WHERE archive_backup.backup_id = backups.id
109                         AND hosts.id=backups.hostid
110                         AND shares.id=backups.shareid
111                         AND archive_backup.archive_id = ?
112         };
113
114         my $sth = $dbh->prepare("SELECT dvd_nr, total_size, note, username, date,id FROM archive WHERE dvd_nr=?");
115         $sth->execute($dvd_nr);
116         my $row = $sth->fetchrow_hashref();
117
118         my $row_h;
119         foreach my $hide (qw/id note/) {
120                 $row_h->{$hide} = $row->{$hide} || '';
121                 delete $row->{$hide};
122         }
123
124         $writer->startTag("archive", %{$row});
125
126         $writer->startTag("note");
127         $writer->characters( $row_h->{'note'} );
128         $writer->endTag("note");
129
130         my $sth_backups = $dbh->prepare( $backups_sql );
131         $sth_backups->execute( $row_h->{'id'} );
132
133         my $total_backups = $sth_backups->rows;
134         my $curr_backup = 0;
135         my $last_pcnt = 0;
136
137         while (my $row = $sth_backups->fetchrow_hashref()) {
138
139                 $curr_backup++;
140                 my $pcnt = int(($curr_backup * 10) / $total_backups);
141                 if ($pcnt > $last_pcnt) {
142                         print " ",(10 - $pcnt);
143                         $last_pcnt = $pcnt;
144                 }
145
146                 my $sth_files = $dbh->prepare( $files_sql);
147                 $sth_files->execute($row->{'backup_id'});
148
149                 delete($row->{'backup_id'});
150                 $row->{'date'} = strftime($t_fmt,gmtime($row->{'date'}));
151
152                 $writer->startTag( "backup", %{$row} );
153
154                 while (my $row = $sth_files->fetchrow_hashref()) {
155                         # convert filetype to string
156                         $row->{'type'} = BackupPC::Attrib::fileType2Text(undef, $row->{'type'});
157                         $row->{'date'} = strftime($t_fmt,gmtime($row->{'date'}));
158                         my $path = $row->{'path'}; delete $row->{'path'};
159
160                         $writer->startTag("file", %{$row});
161                         $writer->characters( $path );
162                         $writer->endTag("file");
163                 }
164                 $writer->endTag("backup");
165         }       
166                          
167         $writer->endTag("archive");
168         $writer->end(); 
169
170         rename $filename.'.tmp', $filename || die "can't rename $filename: $!";
171
172         print "\n";
173 }
174
175
176
177 #----- main
178
179 my $sth = $dbh->prepare( qq{
180 select
181         id,dvd_nr,total_size,note,username,
182         archive.date as date,
183         count(archive_burned.archive_id) as copies
184 from archive
185         left outer join archive_burned on archive.id=archive_burned.archive_id
186 group by id,dvd_nr,total_size,note,username,archive.date
187 order by date asc
188 } );
189
190 $sth->execute();
191
192 sub fmt_archive($) {
193         my $row = shift || die;
194
195         $row->{'date'} =~ s/\.\d+$//;
196         $row->{'copies'} =~ s/^\s*0+\s*$/no/;
197         $row->{'total_size'} /= (1024*1024);
198
199         my $copies = 'copies';
200         $copies = 'copy' if ($row->{'copies'} == 1);
201
202         return
203                 sprintf("%d by %s on %s, %s %s [%.2f Mb]",
204                         $row->{'dvd_nr'},
205                         $row->{'username'},
206                         $row->{'date'},
207                         $row->{'copies'}, $copies,
208                         $row->{'total_size'},
209                 );
210 }
211
212 my @burned;
213 my @not_burned;
214
215 while (my $row = $sth->fetchrow_hashref) {
216         if ($row->{'copies'}) {
217                 push @burned, fmt_archive($row);
218         } else {
219                 push @not_burned, fmt_archive($row);
220         }
221 }
222
223 my %Menu_archive = (
224         Label => 'Menu_archive',
225
226         Item_1 => {
227                 Text => 'DVD #]Convey[',
228                 Convey => [ @not_burned ],
229                 Default => '*',
230         },
231         Item_2 => {
232                 Text => 'DVD #]Convey[',
233                 Convey => [ @burned ],
234         },
235
236         Select => 'Many',
237
238         Banner => "Select one or more DVD media for burning",
239 );
240
241 my @archives_to_burn = Menu(\%Menu_archive);
242
243 print "\n";
244
245 sub skip($) {
246         my $msg = shift;
247         print "WARNING: $msg, skipping...\n";
248         goto SKIP;
249 }
250
251 sub add_symlink($$) {
252         my ($from, $to) = @_;
253         symlink $from, $to || skip("can't symlink $from to $to: $!");
254 }
255
256 my $sth_archive_backup_parts = $dbh->prepare( qq{
257         select
258                 archive_backup.backup_id,
259                 archive_id,
260                 hosts.name as host,
261                 shares.name as share,
262                 backups.num as num,
263                 backups.parts as parts,
264                 backup_parts.part_nr as part_nr,
265                 backup_parts.size as part_size,
266                 backup_parts.md5 as md5,
267                 backup_parts.items
268         from archive_backup
269         join archive on archive_id = archive.id
270         join backups on archive_backup.backup_id = backups.id
271         join hosts on hostid = hosts.id
272         join shares on shareid = shares.id
273         join backup_parts on archive_backup.backup_id = backup_parts.backup_id
274         where archive.dvd_nr = ?
275         order by archive_backup.backup_id, backup_parts.part_nr
276 });
277
278 my $sth_archive_burned = $dbh->prepare( qq{
279         insert into archive_burned
280                 (archive_id, iso_size, part, copy)
281         values ( (select id from archive where dvd_nr =?), ?, ?, ?)
282 });
283
284 foreach my $arc (@archives_to_burn) {
285         exit if ($arc eq ']quit[');
286
287         my $dvd_nr = $1 if ($arc =~ m/DVD #(\d+)/);
288         die "BUG: can't find dvd_nr in $arc\n" unless ($dvd_nr);
289
290         my $tmp_dir = "/$iso_dir/$dvd_nr";
291
292         my $t = time();
293
294         print "Working on DVD #$dvd_nr in $tmp_dir\n";
295
296         $sth_archive_backup_parts->execute($dvd_nr);
297
298         if ($sth_archive_backup_parts->rows == 0) {
299                 warn "ERROR: no backup parts found for $dvd_nr. You should re-create that DVD.\n";
300         }
301
302         my @volumes;
303         my $v;  # emtpy volume
304         my $v_size = 0;
305
306         my $max_archive_size = $Conf{MaxArchiveSize} || die "no MaxArchiveSize";
307         while (my $row = $sth_archive_backup_parts->fetchrow_hashref) {
308                 if (($v->{size} || 0) + $row->{part_size} > $max_archive_size) {
309                         push @volumes, $v;
310                         $v = {};
311                 }
312                 $v->{size} += $row->{part_size};
313                 # this part
314                 my $p = {
315                         filename => BackupPC::SearchLib::getGzipName($row->{'host'}, $row->{'share'}, $row->{'num'}),
316                 };
317                 foreach my $fld (qw/part_nr md5/) {
318                         $p->{$fld} = $row->{$fld} || die "missing $fld in row!";
319                 }
320                 push @{ $v->{parts} }, $p;
321         }
322         push @volumes, $v if ($v);
323
324         #warn "# volumes: ",Dumper(\@volumes),"\n";
325
326         my $volumes = $#volumes + 1;
327         my $volume_nr = 1;
328
329         foreach my $v (@volumes) {
330
331                 #print Dumper($v);
332
333                 my $iso_size = 0;
334                 my $disk_name = $dvd_nr;
335                 # suffix added to multi-volume archives
336                 my $volume_suffix = $dvd_nr;
337
338                 if ($volumes > 1) {
339                         $volume_suffix = '_' . $volume_nr;
340                         $disk_name .= ' ' . $volume_nr . '/' . $volumes;
341                 }
342
343                 print "Processing DVD #$dvd_nr, volume $volume_nr/$volumes\n";
344
345                 my $iso_file = my $xml_file = my $stage =
346                         "${iso_dir}/${dvd_nr}";
347
348                 $iso_file .= $volume_suffix . '.iso';
349                 $xml_file .= '.xml';
350
351                 $stage .= $volume_suffix . '.stage';
352
353                 my $md5_file = "${stage}/${dvd_nr}${volume_suffix}.md5";
354
355                 #
356                 # check if ISO file exists
357                 #
358
359                 if (! -e $iso_file) {
360
361                         # create stage directory
362                         if (-e $stage) {
363                                 rmtree($stage) || die "can't remove $stage: $!";
364                         }
365                         mkpath($stage);
366
367                         # open file for md5sums
368                         open(my $md5, "> $md5_file") || skip "can't open $md5_file: $!";
369
370                         my $parts_on_this_volume = 0;
371
372                         foreach my $p (@{ $v->{parts} }) {
373                                 my $tar_file = $p->{filename} || die "no filename in part", Dumper($p);
374                                 my $rel_path = $tar_file;
375
376                                 if (-d "$tar_dir/$rel_path") {
377                                         mkpath("$stage/$rel_path") unless (-d "$stage/$rel_path");
378                                         $rel_path .= '/' . $p->{part_nr};
379                                 }
380                                 $rel_path .= '.tar.gz';
381
382                                 skip "can't find increment $rel_path: $!" unless (-r "$tar_dir/$rel_path");
383
384                                 add_symlink("$tar_dir/$rel_path", "$stage/$rel_path");
385
386                                 my $md5sum = $p->{md5} || die "no md5 in part ", Dumper($p);
387                                 chomp($md5sum);
388                                 print $md5 "$md5sum  $rel_path\n" || die "can't write md5sum: $!";
389
390                                 $parts_on_this_volume++;
391                         }
392
393                         # add file list and note in xml
394                         dumpArchive2XML($dbh, $dvd_nr, $xml_file) unless (-f $xml_file);
395
396                         add_symlink($xml_file, "$stage/${dvd_nr}.xml");
397
398                         # add css file for archive
399                         my $css_file = $Conf{CgiImageDir} . '/archive.css';
400                         if (-r $css_file) {
401                                 add_symlink($css_file, "$stage/archive.css");
402                         } else {
403                                 print "WARNING: missing $css_file, not added to iso image!\n";
404                         }
405
406                         print "Running mkisofs now for $parts_on_this_volume increments, disk $disk_name\n";
407
408                         my $cmd = $bin->{'mkisofs'} . qq{ -A BackupPC -gui -J -r -T --input-charset ISO-8859-2 -V "$disk_name" -o ${iso_file}.tmp -f $stage };
409
410                         system($cmd) == 0 or skip "can't run $cmd: $?";
411
412                         rename $iso_file.'.tmp', $iso_file || skip "can't rename $iso_file: $!";
413
414                         $iso_size = (stat($iso_file))[7];
415
416                         print "Created $iso_file [$iso_size bytes] in ", fmt_time(time() - $t), "\n";
417
418                         rmtree($stage) || warn "can't remove stage directory $stage: $!";
419
420                 } else {
421                         print "ISO $iso_file allready exists\n";
422                 }
423
424                 my $copies = $Conf{BurnMultipleCopies} || 1;
425
426                 foreach my $copy_nr ( 1 .. $copies ) {
427
428                         print "\nREADY TO BURN MEDIA $disk_name copy $copy_nr\n\nPlease insert blank media and press ENTER\n\n";
429
430                         system($bin->{'eject'}.' '.$eject_opts) == 0 or skip "can't run eject: $?";
431
432                         my $wait = <STDIN>;
433
434                         my $cmd = $bin->{'cdrecord'} . ' ' . $cdr_opts . ' ' . $iso_file;
435
436                         # FIXME
437                         print "## $cmd\n";
438                         system($cmd) == 0 or skip "can't run $cmd: $?";
439
440                         print "\n\nPLEASE REMOVE DVD MEDIA AND LABEL IT WITH $disk_name\n\n";
441
442                         $sth_archive_burned->execute($dvd_nr, $iso_size, $volume_nr, $copy_nr);
443
444                         print "Media burn for $disk_name copy $copy_nr recorded\n";
445                 }
446
447                 $volume_nr++;
448         }
449
450 SKIP:
451
452 }
453
454 #my $tar_file = BackupPC::SearchLib::getGzipName($row->{'host'}, $row->{'share'}, $row->{'num'});
455 #print curr_time, sprintf(" %s:%s %-3d ", $row->{'host'}, $row->{'share'}, $row->{'num'}), " -> $tar_file ";
456
457 print "Recoding finished, exiting...\n";
458
459 $sth->finish;
460 $sth_archive_backup_parts->finish;
461 $sth_archive_burned->finish;
462
463 $dbh->disconnect;
464