#!/usr/bin/perl -w
#

use strict;
use Getopt::Long;
use File::Basename;
use Time::Local;
use POSIX;

my %LC;

sub getLocalConfig(;@) {
	my @vars = @_;
	my $dir = dirname(dirname($0));
	my $cmd = "$dir/bin/zmlocalconfig -q -x";
	if (scalar(@vars) > 0) {
		$cmd .= ' ' . join(' ', @vars);
	}
	open(LCH, "$cmd |") or die "Unable to invoke $cmd: $!";
	my $line;
	while (defined($line = <LCH>)) {
		chomp($line);
		my @fields = split(/\s*=\s*/, $line, 2);
		$LC{$fields[0]} = $fields[1];
	}
	close(LCH);
}

sub userCheck() {
	my $loggedIn = qx(id -un);
	chomp($loggedIn) if (defined($loggedIn));
	my $expected = $LC{zimbra_user};
	if ($loggedIn ne $expected) {
		print STDERR "Must be user $expected to run this command\n";
		exit(1);
	}
}

getLocalConfig('zimbra_user');
userCheck();

sub usage(;$) {
	my $rc = shift;
	if (!defined($rc)) {
		$rc = 1;
	}
	print <<_USAGE_;
Usage: zmbackupqueryldap [options]

 -t,--target <arg>    backup target directory (default = /opt/zimbra/backup)
 -lb,--label <arg>     backup label to query

Queries LDAP backups.
_USAGE_
	exit($rc);
}

sub getLabelTime($) {
    my $label = shift;
    if ($label =~ /-(\d\d\d\d)(\d\d)(\d\d)\.(\d\d)(\d\d)(\d\d)\.(\d\d\d)$/) {
        my ($year, $mon, $day, $hour, $min, $sec, $ms) = ($1, $2, $3, $4, $5, $6, $7);
        my $t = Time::Local::timegm($sec, $min, $hour, $day, $mon - 1, $year);
        return ($t, $ms);
    }
    return (0, 0);
}

sub toLocalTimestamp($;$) {
    my ($time, $ms) = @_;
    $ms |= 0;
    $ms = sprintf("%03d", $ms);
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime($time);
    return POSIX::strftime("%a, %Y/%m/%d %H:%M:%S.$ms %Z", $sec, $min, $hour, $mday, $mon, $year);
}

sub printBackupLabelInfo($$) {
    my ($label, $labelDir) = @_;
    print "Label:   $label\n";

    my ($t, $ms) = getLabelTime($label);
    my $startTime = toLocalTimestamp($t, $ms);
    print "Created: $startTime\n";
}

sub labelCmpDesc {
    my $timeA = getLabelTime($a);
    my $timeB = getLabelTime($b);
    return $timeB <=> $timeA;
}


# main

my $help;
my ($target, $outdir, $label) = ("/opt/zimbra/backup", undef, undef);
my $opts_good = GetOptions(
    'help' => \$help,
    'target=s' => \$target,
    'label=s' => \$label,
    'lb=s' => \$label
);
if (!$opts_good) {
    print STDERR "\n";
    usage();
}
if ($help) {
    usage(0);
}

my $sessionsDir = "$target/sessions";
if (-e $sessionsDir) {
    if (defined($label)) {
        my $labelDir = "$sessionsDir/$label";
        if (-e $labelDir) {
            printBackupLabelInfo($label, $labelDir);
        } else {
            print STDERR "No such backup label: $label\n";
        }
    } else {
        opendir(DIR, $sessionsDir) or die "Unable to open directory $sessionsDir: $!";
        my @labels = grep { /^[^\.]/ } readdir(DIR);
        closedir(DIR);
        @labels = sort labelCmpDesc (@labels);
        foreach my $lb (@labels) {
            my $labelDir = "$sessionsDir/$lb";
            printBackupLabelInfo($lb, $labelDir);
            print "\n";
        }
    }
}
