# This file is in the public domain.
#!/bin/bash
#

# Options are:
# -c FILENAME, --config=FILENAME (where to write config, defaults to ~/.config/taler.conf)
# -C CURRENCY, --currency=CURRENCY (name of the currency)
# -e, --exchange (generate configuration for the exchange)
# -f AMOUNT, --wirefee=AMOUNT (wire transfer fees charged to merchant, generated for next 5 years)
# -j WIREJSON, --wire-json-merchant=WIREJSON (wire plugin details in JSON)
# -J WIREJSON, --wire-json-exchange=WIREJSON (wire plugin details in JSON)
# -m, --merchant (generate configuration for the merchant)
# -t, --trusted (generate configuration for exchange and merchant, with exchange set as trusted with merchant)
# -w WIREFORMAT, --wire=WIREFORMAT (which wire plugin should we use)
# --bank-uri=URI (only for WIREFORMAT='test')
# --exchange-bank-account=NUMBER (only for WIREFORMAT='test')
# --merchant-bank-account=NUMBER (only for WIREFORMAT='test')

##########################################
# set an initial value for the flags
ARG_CONFIG=~/.config/taler.conf
ARG_CURRENCY=
ARG_E=0
ARG_H=0
ARG_JE=
ARG_JM=
ARG_M=0
ARG_T=0
ARG_W=test
ARG_BANK_URI=
ARG_EXCHANGE_BANK_ACCOUNT=
ARG_MERCHANT_BANK_ACCOUNT=

##################################
# read the options
TEMP=`getopt -o c:C:ef:hj:J:mtw: --long config:,currency:,exchange,wirefee:,help,wire-json-exchange:,wire-json-merchant:,merchant,trusted,wire:,bank-uri:,exchange-bank-account:,merchant-bank-account: -n 'taler-config-generate' -- "$@"`
eval set -- "$TEMP"

####################################################
# extract options and their arguments into variables.
while true ; do
    case "$1" in
        -c|--config)
            ARG_CONFIG="$2"
            shift 2 ;;
        -C|--currency)
            ARG_CURRENCY="$2"
            shift 2 ;;
        -e|--exchange)
            ARG_E=1
            shift ;;
        -f|--wirefee)
            ARG_WIRE_FEE="$2"
            shift 2 ;;
        -h|--help)
            ARG_H=1
            shift ;;
        -j|--wire-json-merchant)
            ARG_JM="$2"
            shift 2 ;;
        -J|--wire-json-exchange)
            ARG_JE="$2"
            shift 2 ;;
        -m|--merchant)
            ARG_M=1
            shift ;;
        -t|--trusted)
            ARG_T=1
            shift ;;
        -w|--wire)
            ARG_W="$2"
            shift 2 ;;
        --bank-uri)
            ARG_BANK_URI="$2"
            shift 2 ;;
        --exchange-bank-account)
            ARG_EXCHANGE_BANK_ACCOUNT="$2"
            shift 2 ;;
        --merchant-bank-account)
            ARG_MERCHANT_BANK_ACCOUNT="$2"
            shift 2 ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done

##########################################
# Handle -h
if (test 1 == "$ARG_H")
then
  exec man taler-config-generate
  exit 1
fi

#########################################
# General preparations
CS="taler-config -c $ARG_CONFIG"
touch "$ARG_CONFIG"


#########################################
# Configure currency in main configuration
if (test ! -z "$ARG_CURRENCY")
then
  $CS -s taler -o CURRENCY -V "$ARG_CURRENCY" || exit 1
else
  ARG_CURRENCY=`$CS -s taler -o CURRENCY`
fi

##########################################
# Assemble JSON description of wireformat for "test" if we can
if (test "test" = "$ARG_W")
then
  if (test ! -z "$ARG_BANK_URI" -a ! -z "$ARG_MERCHANT_BANK_ACCOUNT")
  then
    ARG_JM="{\"type\":\"test\",\"bank_uri\":\"$ARG_BANK_URI\",\"account_number\":$ARG_MERCHANT_BANK_ACCOUNT}"
#    echo "Account detail: $ARG_JM"
  else
    echo "Bank URI or account not given, skipping JSON generation for merchant"
  fi
  if (test ! -z "$ARG_BANK_URI" -a ! -z "$ARG_EXCHANGE_BANK_ACCOUNT")
  then
    ARG_JE="{\"type\":\"test\",\"bank_uri\":\"$ARG_BANK_URI\",\"account_number\":$ARG_EXCHANGE_BANK_ACCOUNT}"
#    echo "Account detail: $ARG_JE"
  else
    echo "Bank URI or account not given, skipping JSON generation for exchange"
  fi
else
  echo "Wire format is not 'test', not auto-generating JSON"
fi

###########################################
# Generate merchant-specific configuration
if (test 1 = "$ARG_M")
then
  MASTER_KEY=`$CS -f -s merchant -o KEYFILE`

# Generate master key (if missing)
  if (test ! -e "$MASTER_KEY")
  then
    mkdir -p `dirname "$MASTER_KEY"`
    gnunet-ecc -g 1 "$MASTER_KEY" || exit 1
  fi

  $CS -s merchant -o WIREFORMAT -V "$ARG_W" || exit 1
  $CS -s merchant -o EDATE -V "3 week" || exit 1

  if (test ! -z "$ARG_JM")
  then
    JSONF=`$CS -s merchant-wireformat -o ${ARG_W}_RESPONSE_FILE -f`
    mkdir -p `dirname "$JSONF"`
    echo "$ARG_JM" > "$JSONF" || exit 1
  else
    echo "Skipped generating wire details for merchant"
  fi
else
  echo "Skipped merchant setup"
fi


############################################
# Generate exchange-specific configuration

if (test 1 = "$ARG_E")
then

  MASTER_KEY=`$CS -f -s exchange -o MASTER_PRIV_FILE`

# Generate master key (if missing)
  if (test ! -e "$MASTER_KEY")
  then
    mkdir -p `dirname "$MASTER_KEY"`
    gnunet-ecc -g 1 "$MASTER_KEY" || exit 1
  fi

# Obtain public master key of exchange
  MASTER_PUB=`gnunet-ecc -p "$MASTER_KEY"`

# Setup master public key
  $CS -s exchange -o MASTER_PUBLIC_KEY -V "$MASTER_PUB" || exit 1

# Setup wire transfer methods
  for $WMETHOD in $ARG_W
  do
    $CS -s exchange-wire-$WMETHOD -o ENABLE -V YES || exit 1

# If possible, initialize outgoing wire account details ('test' method only)
    if (test "test" = "$WMETHOD" -a ! -z "$ARG_BANK_URI")
    then
      $CS -s exchange-wire-test -o BANK_URI -V "$ARG_BANK_URI" || exit 1
    else
      echo "Skipped generating wire account details for exchange"
    fi
    if (test "test" = "$ARG_W" -a ! -z "$ARG_EXCHANGE_BANK_ACCOUNT")
    then
      $CS -s exchange-wire-test -o BANK_ACCOUNT_NUMBER -V "$ARG_EXCHANGE_BANK_ACCOUNT" || exit 1
    else
      echo "Skipped generating wire account details for exchange"
    fi

# If possible, initialize /wire response from JSON (with signature)
    if (test ! -z $ARG_JE)
    then
      JSONF=`$CS -s exchange-wire-${ARG_W} -o ${ARG_W}_RESPONSE_FILE -f`
#    echo "Generating /wire response at $JSONF"
      mkdir -p `dirname $JSONF`
      taler-exchange-wire -c "$ARG_CONFIG" -t "$ARG_W" -j "$ARG_JE" -m "$MASTER_KEY" -o "$JSONF" || exit 1
    else
      echo "Skipped generating /wire response for exchange"
    fi

# Setup wire transfer fee structure.
    if (test -z "$ARG_WIRE_FEE")
    then
      today=`date '+%Y'`
      future=`expr $today + 5`
      for YEAR in `seq $today $future`
      do
        $CS -s exchange-wire-$WMETHOD -o wire-fee-$YEAR -V $ARG_WIRE_FEE
      done
    else
      echo "Skipped generating wire fee structure for exchange"
    fi

# End of for loop over all wire transfer methods
  done

else
  echo "Skipped exchange setup"
fi

########################################
# setup trust in exchange with merchant
if (test 1 = "$ARG_T")
then
  if (test 1 = "$ARG_E")
  then
    EPORT=`$CS -s exchange -o PORT`
    $CS -s merchant-exchange-test -o URI -V "http://localhost:$EPORT/" || exit
    $CS -s merchant-exchange-test -o MASTER_KEY -V `$CS -s exchange -o MASTER_PUBLIC_KEY`
  else
    echo "Need to be configuring exchange as well for -t to be useful."
  fi
fi


###################################################
# Generate coin configuration
for FRACTION in 1 2 4 8 16 32 64
do
  SECTION="coin_${ARG_CURRENCY}_ct_${FRACTION}"
  $CS -s $SECTION -o value -V ${ARG_CURRENCY}:0.${FRACTION} || exit 1
  $CS -s $SECTION -o duration_overlap -V "1 day" || exit 1
  $CS -s $SECTION -o duration_withdraw -V "7 days" || exit 1
  $CS -s $SECTION -o duration_spend -V "2 years" || exit 1
  $CS -s $SECTION -o duration_legal -V "3 years" || exit 1
  $CS -s $SECTION -o fee_withdraw -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o fee_deposit -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o fee_refresh -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o fee_refund -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o rsa_keysize -V 1024 || exit 1
done

for VALUE in 1 2 4 8 16 32 64
do
  SECTION="coin_${ARG_CURRENCY}_${VALUE}"
  $CS -s $SECTION -o value -V ${ARG_CURRENCY}:${VALUE} || exit 1
  $CS -s $SECTION -o duration_overlap -V "1 day" || exit 1
  $CS -s $SECTION -o duration_withdraw -V "7 days" || exit 1
  $CS -s $SECTION -o duration_spend -V "2 years" || exit 1
  $CS -s $SECTION -o duration_legal -V "3 years" || exit 1
  $CS -s $SECTION -o fee_withdraw -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o fee_deposit -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o fee_refresh -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o fee_refund -V "${ARG_CURRENCY}:0.01" || exit 1
  $CS -s $SECTION -o rsa_keysize -V 1024 || exit 1
done

#######################################################
# Clean up configuration: only keep differences to defaults
$CS -w || exit


#######################################################
# Let user know what is next...

echo "All done."
if (test "$ARG_E" = 1)
then
  echo "You probably want to run 'taler-exchange-keyup' next."
fi
