#!/bin/sh
##
##  tendermint-init -- Tendermint initialization
##

#   sanity check usage
if [ $# -lt 2 ]; then
    echo "Usage: tendermint-init <chain-id> <local-validator-id> [<remote-validator-id> ...]" 1>&2
    exit 1
fi

#   determine chain id
chainid="$1"
shift

#   iterate over all validators...
validators=""
i=0
for validatorid in "$@"; do
    #   generate priv_validator.json file
    if [ $i -eq 0 ]; then
        file="priv_validator.json"
    else
        file="priv_validator-${validatorid}.json"
    fi
    @l_prefix@/bin/tendermint gen_validator \
        --home @l_prefix@/var/tendermint/db \
        >@l_prefix@/etc/tendermint/$file

    #   generate genesis.json entry
    pubkey="`@l_prefix@/bin/jq -cM .pub_key @l_prefix@/etc/tendermint/$file`"
    if [ $i -gt 0 ]; then
        validators="${validators},"
    fi
    validators="${validators}{ \"name\": \"$validatorid\", \"power\": \"10\", \"pub_key\": $pubkey }"

    i=`expr $i + 1`
done

#   generate genesis.json file
genesis="{"
genesis="${genesis}    \"genesis_time\": \"0001-01-01T00:00:00Z\","
genesis="${genesis}    \"chain_id\": \"$chainid\","
genesis="${genesis}    \"app_hash\": \"\","
genesis="${genesis}    \"validators\": ["
genesis="${genesis}${validators}"
genesis="${genesis}    ]"
genesis="${genesis}}"
echo "$genesis" | @l_prefix@/bin/jq -cM . >@l_prefix@/etc/tendermint/genesis.json

