#!/usr/bin/env perl
use warnings;
use strict;
use 5.014;

if ($#ARGV < 2) {
  say "USAGE: $0 -s msg recipient '$#ARGV'";
  exit 1;
}

sub escape {
    my $arg = shift;

    $arg =~ s/'/'\\''/g;
    return "'" . $arg . "'";
}

my $msg = escape $ARGV[1];
my $recipient = escape $ARGV[2];

die "no job id passed via argv" unless $msg =~ /Job_id=(\d+)/;
my $id = $1;

open my $job_fh, "/var/log/slurm/job_completions"
  or die "Could not open slurms jobcompletion: $!";
my @matches = grep /$id/, <$job_fh>;
close $job_fh;

if ($#matches < 0) {
  die "job id $id not found";
}
$matches[0] =~ s/\s+/\n/g;
my $new_msg = $matches[0];

open my $mail, "| mail -s $msg $recipient";
print $mail $new_msg;
close $mail;
