#!/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)
            # Phone number is required.
            echo "CONTACT_PHONE"
            exit 0
            ;;
        c)
            # shellcheck disable=SC2034
            CONF="$OPTARG"
            ;;
        h)
            echo "This is a KYC measure program that lifts restrictions on withdraw and P2P transfers after a phone number was confirmed via SMS. Expiration rules are set based on the context."
            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 "attributes"
            echo "context"
            echo "current_rules"
            exit 0
            ;;
        r)
            exit 0
            ;;
        v)
            echo "$0 v0.0.2"
            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,"context":.context}')

# Get phone number.
PHONE_NUMBER=$(echo "$INPUTS" | jq -r '.attributes.CONTACT_PHONE // null')
# Get current rules.
CURRENT_RULES=$(echo "$INPUTS" | jq '.current_rules // null')
# Get context values.
EXPIRATION_TIME=$(echo "$INPUTS" | jq '.context.expiration_time // .attributes.expires // .current_rules.expiration_time // null')
SUCCESSOR_MEASURE=$(echo "$INPUTS" | jq '.context.successor_measure // .current_rules.successor_measure // null')
CUSTOM_MEASURES=$(echo "$INPUTS" | jq '.context.custom_measures // null')

# Validate phone number
if eval echo "$PHONE_NUMBER" | grep -E -e "${EXCHANGE_AML_PROGRAM_TOPS_SMS_CHECK_REGEX}" > /dev/null
then
    # Valid phone number
    # Remove limitation from current rules.
    NEW_RULES=$(echo "$CURRENT_RULES" | jq 'del(.rules[] | select ((.rule_name=="p2p-domestic-identification-requirement") or (.rule_name=="withdraw-limit-low") ))')

# Remove test rules that should now be satisfied
NEW_RULES=$(echo "$NEW_RULES" | jq 'del(.rules[] | select (.rule_name=="balance-testing-limit1") )')

    TO_INVESTIGATE="false"
else
    # Invalid phone number
    echo "Phone number ${PHONE_NUMBER} invalid." 1>&2
    NEW_RULES=$(echo "$CURRENT_RULES" | jq '.+{"to_investigate": true}')
    TO_INVESTIGATE="true"
fi


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

exec jq -n \
    --argjson et "$EXPIRATION_TIME" \
    --argjson sm "$SUCCESSOR_MEASURE" \
    --argjson cm "$CUSTOM_MEASURES" \
    --argjson nr "$NEW_RULES" \
    --argjson inv "$TO_INVESTIGATE" \
    '{"new_rules":($nr+{"expiration_time":$et,"successor_measure":$sm,"custom_measures":({}+$nr.custom_measures+$cm)}),"to_investigate":$inv}|del(..|nulls)'
