#!/bin/sh
set -eux
LOG_FILE="$(mktemp)"
{
  finish() {
    status=$?
    if [ $status = 0 ]; then
      STATUS="✅ SUCCESS (status $status)"
    else
      STATUS="❌ FAILURE (status $status)"
    fi

    echo "Registering status locally..."
    set -x
    printf '%s __JOB__\n' "$status" >> "/tmp/cron-dbg.summary.$(date -I).euandreh.log"

    echo "Sending report email..."

    SUBJECT="Job report on $(hostname): ${STATUS} for job-__JOB__.sh"
    gpg -easr eu@euandre.org < "$LOG_FILE" | \
      mail eu@euandre.org           \
          -s "$SUBJECT"            \
          -a 'From:eu@euandre.org' \
          --content-type 'text/plain; charset=utf-8'
    echo 'Mail sent!'
  }
  trap finish EXIT

  echo "Starting: $(date -Is)"
  ~/dev/libre/dotfiles/cron/__JOB__.sh
  echo "Finishing: $(date -Is)"
} | tee "$LOG_FILE" 2>&1
