#!/usr/bin/perl

use strict;
use warnings;
BEGIN { do "/home/mod_perl/hm/ME/FindLibs.pm"; }
use Getopt::Std;
use ME::Machine;
use IO::LockedFile;
use List::Util qw/shuffle/;
use Filesys::Df qw(df);

sub usage {
  die <<EOF
Usage: $0 [-s slot] [-a] [-p] [-f] src dest

  src: comma separated list of tier names
 dest: single tier name

 -a => all slots
 -p => primary slots
 -f => FORCE (don't check for locks)
 -d num => disk usage must be greater than num percent on the /run directory

squatter opts passed through:
 -v -F -X -T temploc -o
EOF
}

my $Lock;

my %Opts;
getopts('s:apvFXT:od:fDN', \%Opts);

unless ($Opts{f}) {
  my $block = 1;
  $block = 0 if $Opts{d}; # just wait for the next one
  $Lock = IO::LockedFile->new({block => $block}, ">/var/lock/xapian_compact.lock");
  die "already running - aborting" unless $Lock;
}

my $src = shift;
my $dest = shift || usage();

foreach my $Slot (shuffle( ME::Machine->ImapSlots())) {
  if ($Opts{a}) {
    # woot
  }
  elsif ($Opts{s}) {
    next unless $Opts{s} eq $Slot->Name();
  }
  elsif ($Opts{p}) {
    next unless $Slot->IsPrimary();
  }
  else {
    next unless $Slot->IsMaster;
  }

  DoSlot($Slot);
}

sub DoSlot {
  my $Slot = shift;
  my $SN = $Slot->Name();

  if ($Opts{d}) {
    my $Path = $Slot->SearchPath();
    my $Usage = df($Path);
    return if $Usage->{per} < $Opts{d};
  }

  my @args = (-z => $dest, -t => $src);
  push @args, '-v' if $Opts{v};
  push @args, '-o' if $Opts{o};
  push @args, '-F' if $Opts{F};
  push @args, '-X' if $Opts{X};
  push @args, ('-T' => $Opts{T}) if $Opts{T};
  my %RunOpts = (
    PrintOutput => 1,
  );
  $RunOpts{Nice} = 1 unless $Opts{N};
  $RunOpts{Daemon} = 1 if $Opts{D};

  $0 = "xapian_compact: $SN";
  $Slot->RunCommand(\%RunOpts, 'squatter', @args);
}

