#!/usr/bin/env bash
# Tested for DB scheme v38: 

set -eu

runuser -u taler-merchant-httpd -- bash -c '
printf "%-38s | %8s | %12s\n" "merchant_id" "payments" "total_amount"
printf "%-38s-+-%-8s-+-%-12s\n" "--------------------------------------" "--------" "------------"

for s in $(psql -t -A taler-merchant -c "
  SELECT schemaname FROM pg_tables 
  WHERE schemaname LIKE '\''merchant_instance_%'\''
    AND tablename = '\''merchant_deposits'\''
"); do
  mid=$(psql -t -A taler-merchant -c "
    SELECT merchant_id FROM merchant.merchant_instances 
    WHERE merchant_serial = ${s#merchant_instance_}
  " 2>/dev/null || echo "?")

  psql -t -A taler-merchant -c "
    SELECT 
      '\''$mid'\'',
      count(*),
      round(
        (COALESCE(sum((amount_with_fee).val), 0) + 
         COALESCE(sum((amount_with_fee).frac), 0)::numeric / 1000000000)
      , 2)
    FROM $s.merchant_deposits
  " 2>/dev/null
done | while read line; do
  printf "%-38s | %8s | %12s\n" $(echo "$line" | tr "|" " ")
done
'
