#!/bin/bash
#
#  This file is part of TALER
#  Copyright (C) 2024 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)
            # Legal entity type is required.
            echo "CUSTOMER_TYPE"
            echo "CUSTOMER_TYPE_VQF"
            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.3"
            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}')

# Get entity type
LEGAL_ENTITY=$(echo "$INPUTS" | jq -r '.attributes.CUSTOMER_TYPE_VQF // null')
# 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 "$LEGAL_ENTITY"
in
    "NATURAL_PERSON")
        FORM="none"
        ;;
    "OPERATIONAL")
        FORM="form-vqf-902.11"
        ;;
    "FOUNDATION")
        # FIXME: #9825: Not yet supported!
        # FORM="vqf-902.12"
        FORM=error
        INVESTIGATE="true"
        ;;
    "TRUST")
        # FIXME: #9027: Not yet supported!
        # FORM="vqf-902.13"
        FORM=error
        INVESTIGATE="true"
        ;;
    "LIFE_INSURANCE")
        # FIXME: #9826: Not yet supported!
        # FORM="vqf-902.15"
        FORM=error
        INVESTIGATE="true"
        ;;
    "OTHER")
        FORM="form-vqf-902.9"
        INVESTIGATE="true"
        ;;
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 legal entity '${LEGAL_ENTITY}'" 1>&2
        NEW_RULES=$(echo "$CURRENT_RULES" | jq '(.rules[] |= if (.measures[0]=="kyx") then .measures=["inform-internal-error"] else . end)')
        INVESTIGATE="true"
        ;;
    "none")
        # Immediately trigger address validation.
        echo "$INPUTS" | taler-exchange-helper-measure-tops-address-check
        exit $?
        ;;
    *)
        # Proceed to FORM.
        echo "Selected VQF form ${FORM}." 1>&2
        # Force user to fill in $FORM
        NEW_RULES=$(echo "$CURRENT_RULES" | jq --arg form "$FORM" '(.rules[] |= if (.measures[0]=="kyx") then .measures=[$form] else . end)')
        NEW_MEASURES="\"$FORM\""
        ;;
esac

# When the information expires, simply ask the user to do the
# same form 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
