Skip to content

Instantly share code, notes, and snippets.

@bkram
Last active March 12, 2018 10:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bkram/db1944a37cd211469163f23e4df5917f to your computer and use it in GitHub Desktop.
Save bkram/db1944a37cd211469163f23e4df5917f to your computer and use it in GitHub Desktop.
perl db-find-missing-attachments.pl /etc/kopano/server.cfg
#!/usr/bin/perl -w
use strict;
use DBI;
my $L1 = 10;
my $L2 = 20;
sub do_error($) {
exit(1);
}
sub readconfig($) {
my ($fn) = @_;
my %options;
open(CFG, $fn) or die("unable to open ".$fn." config file");
while (<CFG>) {
if ($_ =~ /^\s*[#!]/) {
next;
}
if ($_ =~ /^\s*(\S+)\s*=\s*([^\r]+)\r?$/) {
my $idx = $1;
my $val = $2;
chomp($val);
$val =~ s/\s+$//;
$options{$idx} = $val;
}
}
close(CFG);
return %options;
}
# TODO: parse config, and use settings
if(scalar(@ARGV) < 1) {
print "Usage: $0 <server.cfg>\n";
exit(1);
}
my $servercfg = $ARGV[0];
$servercfg = "/etc/kopano/server.cfg" if (!defined($servercfg));
my %serveropt = readconfig($servercfg);
my $basepath = $serveropt{attachment_path};
my $db = DBI->connect("dbi:mysql:database=".$serveropt{mysql_database}.";host=".$serveropt{mysql_host}, $serveropt{mysql_user}, $serveropt{mysql_password})
or die "Database error: ".$DBI::errstr;
my $res;
my $sth;
my $rows;
my @row;
my $state;
if (!defined($db)) {
print "did not connect to mysql\n";
exit(1);
}
print "Finding all attachments...\n";
$sth = $db->prepare("SELECT DISTINCT(instanceid) FROM singleinstances LEFT JOIN hierarchy ON hierarchyid=hierarchy.id WHERE hierarchy.id IS NOT NULL;");
$sth->execute() || die $DBI::errstr;;
if ($sth->rows == 0) {
print "No attachments found.\n";
exit(0);
}
if ($serveropt{attachment_storage} eq "files") {
print "Processing ".$sth->rows." attachments\n";
while(@row = $sth->fetchrow_array()) {
$state = '0';
my $filename = $basepath."/".($row[0] % $L1)."/".(($row[0] / $L1) % $L2)."/".$row[0];
if (-e $filename) {
$state = '1';
}
elsif ( -e "$filename.gz" ){
$state = '1';
}
if ($state != '1') {
print "Missing attachment file: $filename\n";
}
}
}
$res = $db->do("begin;");
if(!$res) {
do_error(1);
}
print "Done.\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment