#!/bin/bash
#
#  This file is part of TALER
#  Copyright (C) 2025 Taler Systems SA
#
#  TALER is free software; you can redistribute it and/or modify it under the
#  terms of the GNU General Public License as published by the Free Software
#  Foundation; either version 3, or (at your option) any later version.
#
#  TALER is distributed in the hope that it will be useful, but WITHOUT ANY
#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
#  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along with
#  TALER; see the file COPYING.  If not, If not, see <http://www.gnu.org/license>
#

# Hard error reporting on.
set -eu


# Exit, with error message (hard failure)
function exit_fail() {
    echo " FAIL: " "$@" >&2
    EXIT_STATUS=1
    exit "$EXIT_STATUS"
}

CONF="$HOME/.config/taler-exchange.conf"
VERBOSE=0

while getopts 'ac:hirvV' OPTION;
do
    case "$OPTION" in
        a)
            exit 0
            ;;
        c)
            # shellcheck disable=SC2034
            CONF="$OPTARG"
            ;;
        h)
            echo "This is an AML program that asks the customer to validate an email address given to the measure from the context. It is to be used when AML officers want a specific address to be validated via postal letter."
            echo 'Supported options:'
            echo '  -a           -- show required attributes'
            # shellcheck disable=SC2016
            echo '  -c $CONF     -- set configuration'
            echo '  -h           -- print this help'
            echo '  -i           -- show required inputs'
            echo '  -r           -- show required context'
            echo '  -v           -- show version'
            echo '  -V           -- be verbose'
            exit 0
            ;;
        i)
            # Need attributes, context and current_rules.
            echo "context"
            echo "current_rules"
            exit 0
            ;;
        r)
            echo "CONTACT_EMAIL"
            exit 0
            ;;
        v)
            echo "$0 v0.0.1"
            exit 0
            ;;
        V)
            VERBOSE=1
            ;;
        ?)
        exit_fail "Unrecognized command line option"
        ;;
    esac
done

if [ 1 = "$VERBOSE" ]
then
    echo "Running $0" 1>&2
fi

# See https://docs.taler.net/taler-kyc-manual.html#tsref-type-AmlProgramInput
# for the full JSON with possible inputs.

# First, extract inputs we need
INPUTS=$(jq '{"current_rules":.current_rules,"context":.context}')

# Get address data
CONTACT_EMAIL=$(echo "$INPUTS" | jq -r '.context.CONTACT_EMAIL')

# Convert address data to Challenger format as best we can.
ADDRESS=$(jq -n \
    --argjson contact_email \""$CONTACT_EMAIL"\" \
    '{"CONTACT_EMAIL":$contact_email,"read_only":true}')

# Get current rules.
CURRENT_RULES=$(echo "$INPUTS" | jq '.current_rules // null')
# Get context values.
EXPIRATION_TIME=$(echo "$INPUTS" | jq '.context.expiration_time // .current_rules.expiration_time // null')
# Get successor measure from current rules, if any (still applies if this new measure expires)
CSUCCESSOR_MEASURE=$(echo "$INPUTS" | jq '.current_rules.successor_measure // null')
# Context for AML program EXEC_NAME, if any.
NEXT_CONTEXT=$(echo "$INPUTS" | jq '.context.next_context // {}')
# Get successor program from context
EXEC_NAME=$(echo "$INPUTS" | jq '.context.exec_name // "taler-exchange-helper-measure-inform-investigate"')

# Define custom measure for address validation.
# We always first run a program to clear the address validation measure,
# and then run whatever program we were given from the context (if any).
# If none was given in the context, we run 'inform-investigate'.
CUSTOM_AMEASURES=$(jq -n \
    --argjson address "$ADDRESS" \
    --argjson en "$EXEC_NAME" \
    --argjson nc "$NEXT_CONTEXT" \
    '{"custom-email-investigation":{"context":{"initial_address":$address,"exec_name":$en,"next_context":$nc,"clear_measure":"custom-email-investigation"},"check_name":"email-registration","prog_name":"clear-measure-and-continue"}}')

# Finally, output the new rules.
# See https://docs.taler.net/taler-kyc-manual.html#tsref-type-AmlOutcome
# for the required output format.

jq -n \
    --argjson et "$EXPIRATION_TIME" \
    --argjson sm "$CSUCCESSOR_MEASURE" \
    --argjson nm '"custom-email-investigation"' \
    --argjson cma "$CUSTOM_AMEASURES" \
    --argjson nr "$CURRENT_RULES" \
    '{"new_measures":$nm,"new_rules":($nr+{"expiration_time":$et,"successor_measure":$sm,"custom_measures":({}+$nr.custom_measures+$cma)})}|del(..|nulls)'

exit 0
