#!/usr/bin/perl -w

use strict;
use File::Copy qw( copy );
use File::Find qw( find );
use File::Basename;

my $restore_from  = $ARGV[0];
my $restore_to    = $ARGV[1];
my $sleep         = 60; # Seconds
my $triggered     = 0;
my $trigger_file  = "/var/lib/pgsql/trigger_startup";

my $last_cp;

exit 1 unless (defined $restore_from and defined $restore_to);

# main
if ( $restore_from =~ /.*history/ ) {
  exit(copyfunc());
}

# sleep until next log replay or triggered
while ( ! -f $restore_from and ! $triggered ) {
  cleanup();
  sleep $sleep;
  $triggered = 1 if ( -e $trigger_file );
}
exit(copyfunc());

# copy file for restore
sub copyfunc {
  unless ($triggered) {
    return 1 if ( -f $restore_to );
    return 0 if (copy($restore_from, $restore_to));
    return 1;
  }
}

sub cleanup {
  my $fh;
  open($fh, "LC_ALL=POSIX pg_controldata .|") || return;

  my ($serial, $timeline);

  while (my $line = <$fh>) {
    if ($line =~ /Latest checkpoint location:\s+([0-9a-f]+)\/([0-9a-f]{1,2})\S{6}/i) {
      $serial = sprintf("%08s%08s", $1, $2);
    }
    if ($line =~ /Latest checkpoint.*?TimeLineID:\s+([0-9a-f]+)/i) {
      $timeline = sprintf("%08s", $1);
    }
  }
  undef $fh;

  return unless ($timeline and $serial);

  if ($last_cp = $timeline.$serial) {
    #print "latest checkpoint serial: ".$last_cp."\n";

    my @dirs;
    push @dirs, dirname($restore_from);

    find(\&wanted, @dirs);
  }
}

sub wanted {
  if ($last_cp gt $_) {
    return if ($_ =~ /\.\.?/);

    #print "unlinking ".$File::Find::name."\n";
    unlink $File::Find::name;
  }
}
