#!/usr/bin/perl

#  This runs out of a cron job on the p4d host, taking a checkpoint
#  and tarring up the file archive, then mailing to the backup storage
#  host, which ftps to grab the backup files.
#

use Carp;
use strict;
$| = 1;

my $Myname;
($Myname = $0) =~ s%^.*/%%;

my $P4root		= shift;
my $P4port		= shift;
my $P4user		= shift;
my $P4passwd		= shift;
my $Depots		= shift;
my $Ftp_dir		= shift;
my $Ftp_prefix		= shift;
my $Notify_email	= shift;

$Ftp_prefix = "$Ftp_dir/$Ftp_prefix";

chdir $P4root || die "chdir ($P4root): $!";

my ($sts, $output) = &s("/bin/rm -f $Ftp_prefix.*");
if ($sts) { die $output; }

my $P4 = "/usr/local/bin/p4 -p $P4port -u $P4user -P $P4passwd";

my ($sts, $output) = &s("$P4 admin checkpoint -z $Ftp_prefix");
if ($sts) { die $output; }

my ($sts, $output) = &s("$P4 counter journal");
if ($sts) { die $output; }

my $c = $output; chomp $c;

my ($sts, $output) = &s("/usr/bin/tar czf $Ftp_prefix.$c.tar.gz $Depots");
if ($sts) { die $output; }

my ($sts, $output) = &s("/usr/bin/touch $Ftp_prefix.$c");
if ($sts) { die $output; }

open (M, "| /usr/sbin/sendmail $Notify_email") || die "open | /usr/sbin/sendmail $Notify_email: $!";
print M <<EOM;
To: $Notify_email
Subject: $Myname: $Ftp_prefix.$c done

$Ftp_prefix.$c done
EOM

exit 0;

#  Run a command, returning status and output; terminate
#  on any error.
#  
sub s
{
  my ($cmd) = @_;
  my ($sts, $output);

  print("> $cmd\n");

  if (! open(CMD, "$cmd 2>&1 |"))
    { die "can't open \"$cmd 2>&1 |\": $!"; }
  
  while (<CMD>) { print(": $_"); $output .= $_; }
  close CMD;

  if ($sts = $?)
    {
      my $sig = $sts & 0x0f;
      $sts = $sts >> 8;
      die "\"$cmd\" exited with signal $sig status $sts";
    }
  return ($sts, $output);
}