#!/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)
            # Controlling entity 3rd person field is required.
            echo "THIRD_PARTY_OWNERSHIP"
            exit 0
            ;;
        c)
            # shellcheck disable=SC2034
            CONF="$OPTARG"
            ;;
        h)
            echo "This is a KYC measure program that determines the next VQF form to ask for (if any) based on the type of legal entity the customer claimed to be on the primary form."
            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 context and current_rules.
            echo "attributes"
            echo "current_rules"
            exit 0
            ;;
        r)
            # Nothing needed from context
            exit 0
            ;;
        v)
            echo "$0 v0.0.4"
            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,"attributes":.attributes}')

# Check form ID, must be 'vqf-902.11'
FORM_ID=$(echo "$INPUTS" | jq -r '.attributes.FORM_ID')

# The 'form' here should be the VQF 902.11 customer form
if [ "$FORM_ID" != "vqf_902_11_customer" ]
then
    echo "Unexpected form ID $FORM_ID" 1>&2
    exec taler-exchange-helper-measure-freeze
fi

# Check all mandatory attributes are present.
echo "$INPUTS" \
    | jq '.attributes' \
    | jq -r 'def get($k):
             if has($k)
               then .[$k]
               else error("attribute \($k) missing")
           end;
           {"THIRD_PARTY_OWNERSHIP":get("THIRD_PARTY_OWNERSHIP"),
            "CONTROL_REASON":get("CONTROL_REASON"),
            "SIGN_DATE":get("SIGN_DATE"),
            "SIGNATURE":get("SIGNATURE")}' \
                > /dev/null \
                || exec taler-exchange-helper-measure-freeze


# Get entity type
CONTROL3P=$(echo "$INPUTS" | jq -r '.attributes.THIRD_PARTY_OWNERSHIP')
# 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')

FORM="error"

INVESTIGATE="false"
case "$CONTROL3P"
in
    "false")
        FORM="none"
    ;;
    "true")
        FORM="vqf-902.9"
    ;;
esac

NEW_MEASURES="null"
# Check high-level case
case "$FORM"
in
    "error")
        # This should not happen, immediately trigger investigation and show error to the user.
        echo "ERROR: Unexpected value for controlling entity is 3rd person '${CONTROL3P}'" 1>&2
        NEW_RULES=$(echo "$CURRENT_RULES" | jq '(.rules[] |= if (.rule_name=="deposit-limit-zero" or .measures[0] == "form-vqf-902.11") then .measures=["inform-internal-error"] else . end)')
        INVESTIGATE="true"
        ;;
    "none")
        # Move into investigation mode.
        echo "INFO: Passing data to taler-exchange-helper-measure-inform-investigate" 1>&2
        NEW_RULES=$(echo "$CURRENT_RULES" | jq '(.rules[] |= if (.rule_name=="deposit-limit-zero" or .measures[0] == "form-vqf-902.11") then .measures=["form-'${FORM}'"] else . end)')
        echo "$INPUTS" | taler-exchange-helper-measure-inform-investigate
        exit $?
        ;;
    *)
        # Proceed to FORM.
        echo "Selected VQF form ${FORM}." 1>&2
        # Force user to fill in $FORM
        NEW_RULES=$(echo "$CURRENT_RULES" | jq '(.rules[] |= if (.rule_name=="deposit-limit-zero" or .measures[0] == "form-vqf-902.11") then .measures=["form-'${FORM}'"] else . end)')
        NEW_MEASURES='"form-'${FORM}'"'
        ;;
esac

# When the information expires, we start the full KYX process
# again.
SUCCESSOR_MEASURE='"kyx"'

# 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 inv "$INVESTIGATE" \
    --argjson et "$EXPIRATION_TIME" \
    --argjson sm "$SUCCESSOR_MEASURE" \
    --argjson nm "$NEW_MEASURES" \
    --argjson nr "$NEW_RULES" \
    '{"to_investigate":$inv,"new_measures":$nm,"new_rules":($nr+{"expiration_time":$et,"successor_measure":$sm,"custom_measures":({}+$nr.custom_measures)})}|del(..|nulls)'

exit 0
