#!/usr/local/bin/perl use strict; use lib "/usr/local/BackupPC/lib"; use DBI; use BackupPC::Lib; use BackupPC::Search; use Time::HiRes qw/time/; use POSIX qw/strftime/; use Term::Menus; use File::Which; use File::Path; use Cwd qw/abs_path/; use Data::Dumper; my $debug = $ENV{DEBUG} || 1; # set this to 1 to prompt for DVD removal for each selected item. my $prompt_for_delete = shift @ARGV; $|=1; # don't check for user my $bpc = BackupPC::Lib->new(undef, undef, 1) || die; $bpc->ConfigRead('_search_archive'); my %Conf = $bpc->Conf(); %BackupPC::Search::Conf = %Conf; my $conf_bin; $conf_bin->{'cdrecord'} = $Conf{CDRecordBin} || die "Need CDRecordBin in config.pl\n"; my $cdr_opts = $Conf{CDRecordOpts} || die "Need CDRecordOpts in config.pl\n"; $conf_bin->{'eject'} = $Conf{ejectBin} || die "Need ejectBin in config.pl\n"; my $eject_opts = $Conf{ejectOpts} || die "Need ejectOpts in config.pl\n"; $conf_bin->{'mkisofs'} = $Conf{mkisofsBin} || die "Need mkisofsBin in config.pl\n"; my $path = abs_path($0); $path =~ s#/[^/]+$#/#; my $tarIncCreate = $path .= 'BackupPC_tarIncCreate'; my $bin; foreach my $c (qw/cdrecord eject mkisofs/) { $bin->{$c} = which($conf_bin->{$c}) || die "$0 needs $c ($conf_bin->{$c}), install it\n"; } my $start_t = time(); my $t_fmt = '%Y-%m-%d %H:%M:%S'; my $dsn = $Conf{SearchDSN} || die "Need SearchDSN in config.pl\n"; my $user = $Conf{SearchUser} || ''; my $dbh = DBI->connect($dsn, $user, "", { RaiseError => 1, AutoCommit => 1 }); my $tar_dir = $Conf{ArchiveDest} || die "ArchiveDest isn't defined in configuration"; #die "problem with $tar_dir, check GzipTempDir in configuration\n" unless -d $tar_dir; my $iso_dir = $Conf{ArchiveDest}.'/iso'; if ( ! -e $iso_dir ) { mkdir $iso_dir || die "can't create $iso_dir: $!"; } #---- subs ---- sub df_bytes_available { my $path = shift; my $out = `df -P $path`; my $bytes = (split(/\s+/, (split(/\n/,$out))[-1]))[3]; return $bytes * 1024; } sub fmt_time { my $t = shift || return; my $out = ""; my ($ss,$mm,$hh) = gmtime($t); $out .= "${hh}h" if ($hh); $out .= sprintf("%02d:%02d", $mm,$ss); return $out; } sub curr_time { return strftime($t_fmt,localtime()); } sub dumpArchive2XML($$$) { my ($dbh, $dvd_nr, $filename) = @_; my %archive; my $output = new IO::File('> '.$filename.'.tmp'); my $writer = new XML::Writer(OUTPUT=>$output, NEWLINES => 1); print "Dumping file list for DVD $dvd_nr, countdown:"; $writer->pi('xml-stylesheet', 'href="archive.css" type="text/css"'); my $files_sql = q{ SELECT files.path AS path, files.date AS date, files.type AS type, files.size AS size FROM files, backups, shares WHERE files.backupnum=backups.num AND files.shareid=shares.id AND shares.hostid=backups.hostid AND backups.id=? }; my $backups_sql = q{ SELECT backup_id, backup_part_id, host, num, date, share, size FROM archive_backup_parts WHERE archive_id = ? ORDER BY backup_part_id }; my $sth = $dbh->prepare("SELECT dvd_nr, total_size, note, username, date, id FROM archive WHERE dvd_nr=?"); $sth->execute($dvd_nr); my $row = $sth->fetchrow_hashref(); my $row_h; foreach my $hide (qw/id note/) { $row_h->{$hide} = $row->{$hide} || ''; delete $row->{$hide}; } $writer->startTag("archive", %{$row}); $writer->startTag("note"); $writer->characters( $row_h->{'note'} ); $writer->endTag("note"); my $sth_backups = $dbh->prepare( $backups_sql ); $sth_backups->execute( $row_h->{'id'} ); my $total_backups = $sth_backups->rows; my $curr_backup = 0; my $last_pcnt = 0; while (my $row = $sth_backups->fetchrow_hashref()) { $curr_backup++; my $pcnt = int(($curr_backup * 10) / $total_backups); if ($pcnt > $last_pcnt) { print " ",(10 - $pcnt); $last_pcnt = $pcnt; } my $sth_files = $dbh->prepare( $files_sql); $sth_files->execute($row->{'backup_id'}); delete($row->{'backup_id'}); $row->{'date'} = strftime($t_fmt,gmtime($row->{'date'})); $writer->startTag( "backup", %{$row} ); while (my $row = $sth_files->fetchrow_hashref()) { # convert filetype to string $row->{'type'} = BackupPC::Attrib::fileType2Text(undef, $row->{'type'}); $row->{'date'} = strftime($t_fmt,gmtime($row->{'date'})); my $path = $row->{'path'}; delete $row->{'path'}; $writer->startTag("file", %{$row}); $writer->characters( $path ); $writer->endTag("file"); } $writer->endTag("backup"); } $writer->endTag("archive"); $writer->end(); rename $filename.'.tmp', $filename || die "can't rename $filename: $!"; print "\n"; } #----- main my $sth = $dbh->prepare( qq{ select id,dvd_nr,total_size,note,username, archive.date as date, count(archive_burned.archive_id) as copies from archive left outer join archive_burned on archive.id=archive_burned.archive_id group by id,dvd_nr,total_size,note,username,archive.date order by date asc } ); $sth->execute(); sub fmt_mb($) { my $s = shift; die "missing size" unless defined($s); $s /= (1024*1024); return sprintf("%.2f Mb", $s); } sub fmt_archive($) { my $row = shift || die; $row->{'date'} =~ s/\.\d+$//; $row->{'copies'} =~ s/^\s*0+\s*$/no/; my $copies = 'copies'; $copies = 'copy' if ($row->{'copies'} == 1); return sprintf("%d by %s on %s, %s %s [%s]", $row->{'dvd_nr'}, $row->{'username'}, $row->{'date'}, $row->{'copies'}, $copies, fmt_mb($row->{'total_size'}), ); } my @burned; my @not_burned; while (my $row = $sth->fetchrow_hashref) { if ($row->{'copies'}) { push @burned, fmt_archive($row); } else { push @not_burned, fmt_archive($row); } } my %Menu_archive = ( Label => 'Menu_archive', Item_1 => { Text => 'DVD #]Convey[', Convey => [ @not_burned ], Default => '*', }, Item_2 => { Text => 'DVD #]Convey[', Convey => [ @burned ], }, Select => 'Many', Banner => "Select one or more DVD media for burning", ); my @archives_to_burn = Menu(\%Menu_archive); print "\n"; sub skip($) { my $msg = shift; print "WARNING: $msg, skipping...\n"; goto SKIP; } sub add_symlink($$) { my ($from, $to) = @_; symlink $from, $to || skip("can't symlink $from to $to: $!"); } sub delete_dvd($) { my $dvd_nr = shift || return; print "Do you want to delete DVD #$dvd_nr now? [NO/yes]: "; my $ok = ; chomp($ok); if (lc($ok) eq 'yes') { print "Deleting DVD #$dvd_nr from database...\n"; $dbh->begin_work; my $sth_delete_dvd = $dbh->prepare( qq{ delete from archive where dvd_nr = ? } ); $sth_delete_dvd->execute( $dvd_nr ); $dbh->do( qq{ select setval('dvd_nr', (select max(dvd_nr) from archive), true) } ); # remove files for this DVD map { if (-d $_) { print "\tremoving dir $_\n"; rmtree($_) || die "can't rmtree $_: $!"; } else { print "\tremoving $_\n"; unlink($_) || die "can't rm $_: $!"; } } glob ( "/$iso_dir/$dvd_nr.*" ); $dbh->commit; return 1; } else { return 0; } } my $sth_archive_backup_parts = $dbh->prepare( qq{ SELECT backup_id, archive_id, host, share, num, part_nr, parts, size, md5, items, filename FROM archive_backup_parts WHERE dvd_nr = ? ORDER BY backup_id, part_nr }); my $sth_archive_burned = $dbh->prepare( qq{ insert into archive_burned (archive_id, iso_size, part, copy) values ( (select id from archive where dvd_nr =?), ?, ?, ?) }); my $copies = $Conf{BurnMultipleCopies} || 1; foreach my $copy_nr ( 1 .. $copies ) { foreach my $arc (@archives_to_burn) { exit if ($arc eq ']quit['); my $dvd_nr = $1 if ($arc =~ m/DVD #(\d+)/); die "BUG: can't find dvd_nr in $arc\n" unless ($dvd_nr); my $tmp_dir = "/$iso_dir/$dvd_nr"; my $t = time(); print "Working on DVD #$dvd_nr in $tmp_dir\n"; $sth_archive_backup_parts->execute($dvd_nr); if ($sth_archive_backup_parts->rows == 0) { warn "ERROR: no backup parts found for $dvd_nr. You should re-create that DVD.\n"; next if delete_dvd( $dvd_nr ); } if ($prompt_for_delete) { next if delete_dvd( $dvd_nr ); } my @volumes; my $v; # emtpy volume my $v_size = 0; my $max_archive_size = $Conf{ArchiveMediaSize} || die "no ArchiveMediaSize"; while (my $row = $sth_archive_backup_parts->fetchrow_hashref) { if (($v->{size} || 0) + $row->{size} > $max_archive_size) { push @volumes, $v; $v = {}; } $v->{size} += $row->{size}; $v_size += $row->{size}; # this part my $p; $p->{$_} = $row->{$_} foreach (qw( filename host share num part_nr md5 )); # include minimun number of columns in XML output push @{ $v->{parts} }, $p; } push @volumes, $v if ($v); warn "# volumes: ",Dumper(\@volumes)," total size: ", fmt_mb($v_size), "\n" if $debug; # check available disk space my $df = df_bytes_available($iso_dir); if ($df < $v_size) { warn "ABORTED: not enough disk space to create ISO ! [need ", fmt_mb($v_size), " have ", fmt_mb( $df ), " on $iso_dir]\n"; next; } my $volumes = $#volumes + 1; my $volume_nr = 1; foreach my $v (@volumes) { #print Dumper($v); my $iso_size = 0; my $disk_name = $dvd_nr; # suffix added to multi-volume archives my $volume_suffix = ''; if ($volumes > 1) { $volume_suffix = '_' . $volume_nr; $disk_name .= ' ' . $volume_nr . '/' . $volumes; } print "Processing DVD #$dvd_nr, volume $volume_nr/$volumes [", fmt_mb($v->{size}), "]\n"; my $iso_file = my $xml_file = my $stage = "${iso_dir}/${dvd_nr}"; $iso_file .= $volume_suffix . '.iso'; $xml_file .= '.xml'; $stage .= $volume_suffix . '.stage'; my $md5_file = "${stage}/${dvd_nr}${volume_suffix}.md5"; # # check if ISO file exists # if (! -e $iso_file) { # create stage directory if (-e $stage) { rmtree($stage) || die "can't remove $stage: $!"; } mkpath($stage); # open file for md5sums open(my $md5, "> $md5_file") || skip "can't open $md5_file: $!"; my $parts_on_this_volume = 0; foreach my $p (@{ $v->{parts} }) { my $tar_file = $p->{filename} || die "no filename in part", Dumper($p); die "ERROR: increment missing $tar_file:$!" unless -r "$tar_dir/$tar_file"; add_symlink("$tar_dir/$tar_file", "$stage/$tar_file"); my $md5sum = $p->{md5} || die "no md5 in part ", Dumper($p); chomp($md5sum); print $md5 "$md5sum $tar_file\n" || die "can't write md5sum: $!"; $parts_on_this_volume++; } # add file list and note in xml dumpArchive2XML($dbh, $dvd_nr, $xml_file) unless (-f $xml_file); add_symlink($xml_file, "$stage/${dvd_nr}.xml"); # add css file for archive my $css_file = $Conf{CgiImageDir} . '/archive.css'; if (-r $css_file) { add_symlink($css_file, "$stage/archive.css"); } else { print "WARNING: missing $css_file, not added to iso image!\n"; } print "Running mkisofs now for $parts_on_this_volume increments, disk $disk_name\n"; 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 }; system($cmd) == 0 or skip "can't run $cmd: $?"; rename $iso_file.'.tmp', $iso_file || skip "can't rename $iso_file: $!"; $iso_size = (stat($iso_file))[7]; print "Created $iso_file [$iso_size bytes] in ", fmt_time(time() - $t), "\n"; rmtree($stage) || warn "can't remove stage directory $stage: $!"; } else { $iso_size = (stat($iso_file))[7]; print "ISO $iso_file already exists [$iso_size bytes]\n"; } print "\nREADY TO BURN MEDIA $disk_name copy $copy_nr\n\nPlease insert blank media and press ENTER\n\n"; system($bin->{'eject'}.' '.$eject_opts) == 0 or skip "can't run eject: $?"; my $wait = ; my $cmd = $bin->{'cdrecord'} . ' ' . $cdr_opts . ' ' . $iso_file; # FIXME print "## $cmd\n"; system($cmd) == 0 or skip "can't run $cmd: $?"; print "\n\nPLEASE REMOVE DVD MEDIA AND LABEL IT WITH $disk_name\n\n"; $sth_archive_burned->execute($dvd_nr, $iso_size, $volume_nr, $copy_nr); print "Media burn for $disk_name copy $copy_nr recorded\n"; if ($copy_nr >= $copies) { print STDERR "erasing temporary files, have $copy_nr copies (> $copies)\n"; foreach my $f (( $xml_file, $iso_file )) { print STDERR "\t$f "; unlink $f || die "can't remove $f: $!"; print STDERR "removed\n"; } } $volume_nr++; } } SKIP: } #my $tar_file = BackupPC::Search::getGzipName($row->{'host'}, $row->{'share'}, $row->{'num'}); #print curr_time, sprintf(" %s:%s %-3d ", $row->{'host'}, $row->{'share'}, $row->{'num'}), " -> $tar_file "; print "Recoding finished, exiting...\n"; $sth->finish; $sth_archive_backup_parts->finish; $sth_archive_burned->finish; $sth_archive_burned->finish; $dbh->disconnect;