#!/bin/bash
# This file is in the public domain.
# Transmit a Challenger TAN by electronic mail.
#
# Usage:
#   echo "MESSAGE" | $0 '{"CONTACT_EMAIL":"user@example.com"}'
#
# The TAN is part of the message read from stdin and never appears in argv.
#
# Exit codes (see challenger-send-email(1)).  Success is 0 or the 200-210
# band; every other value is a failure.  The success band is up at 200 and
# not at 1 because libgnunetutil reports a failed exec() of the helper as
# exit code 1, which must not be mistaken for a delivery.
# Handing a message to a mail transfer agent only establishes that the agent
# accepted it, so this helper never reports 0.
#
#  201  accepted for delivery by the local mail transfer agent
#   10  address malformed or missing
#   30  the local mail transfer agent failed
#   40  local configuration or invocation error
#   50  unclassified failure

set -eu

if [ $# -ne 1 ]
then
    echo "Usage: $0 '{\"CONTACT_EMAIL\":\"user@example.com\"}'" 1>&2
    exit 40
fi

EMAIL=$(echo "$1" | jq -r '.CONTACT_EMAIL // empty')

if [ -z "$EMAIL" ]
then
    echo "No CONTACT_EMAIL field in the address object" 1>&2
    exit 10
fi

if [[ ! "$EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]]
then
    echo "Address '$EMAIL' is not a valid e-mail address" 1>&2
    exit 10
fi

if ! command -v mail > /dev/null
then
    echo "mail(1) is not installed" 1>&2
    exit 40
fi

STATUS=0
mail -s "KYC Challenger" -r noreply "$EMAIL" || STATUS=$?

if [ 0 -ne "$STATUS" ]
then
    echo "mail(1) failed with status $STATUS sending to $EMAIL" 1>&2
    exit 30
fi

exit 201
