# shellcheck shell=bash
# Common helpers for Taler sanity checks (run on koopa host as root).
# shellcheck disable=SC2034

: "${BANK_URL:=http://127.0.0.1:9012}"
: "${MERCHANT_URL:=https://127.0.0.1:9010}"
: "${EXCHANGE_PUBLIC:=https://exchange.hacktivism.ch}"
: "${BANK_PUBLIC:=https://bank.hacktivism.ch}"
: "${MERCHANT_PUBLIC:=https://taler.hacktivism.ch}"

pass() { echo "OK  $*"; }
fail() { echo "FAIL $*"; FAILS=$((FAILS + 1)); }
warn() { echo "WARN $*"; }
info() { echo "INFO $*"; }

FAILS=0

need_root() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "This check expects root on koopa (password files under /root)." >&2
    exit 2
  fi
}

read_pw() {
  # read_pw VAR path
  local _v="$1" _p="$2"
  if [ ! -f "$_p" ]; then
    eval "$_v="
    return 1
  fi
  eval "$_v=\$(tr -d '\\n' <\"$_p\")"
}

bank_token() {
  # bank_token USER PASS -> prints access_token
  local user="$1" pass="$2"
  curl -sS -m 15 -u "${user}:${pass}" \
    -H 'Content-Type: application/json' \
    -d '{"scope":"readwrite","refreshable":true}' \
    "${BANK_URL}/accounts/${user}/token" \
    | python3 -c 'import sys,json; print(json.load(sys.stdin).get("access_token",""))'
}

merchant_auth_header() {
  # merchant_auth_header PASSWORD
  printf 'Authorization: Bearer secret-token:%s' "$1"
}

http_code() {
  # http_code URL [curl args...]
  local url="$1"
  shift
  curl -sk -m 12 -o /dev/null -w '%{http_code}' "$@" "$url" 2>/dev/null || echo "000"
}

json_get() {
  # json_get FILE python-expr-on-d
  python3 -c "import json,sys; d=json.load(open(sys.argv[1])); print($2)" "$1"
}
