#!/usr/bin/env bash

# exit from script if error was raised.
set -e

# error function is used within a bash function in order to send the error
# message directly to the stderr output and exit.
error() {
    echo "$1" > /dev/stderr
    exit 0
}

# return is used within the bash function in order to return the value.
return() {
    echo "$1"
}

# set_default function gives the ability to move the setting of default
# env variable from docker file to the script thereby giving the ability to the
# user to override it during container start.
set_default() {
    # docker initialized env variables with blank string and we can't just
    # use -z flag as usually.
    BLANK_STRING='""'

    VARIABLE="$1"
    DEFAULT="$2"

    if [[ -z "$VARIABLE" || "$VARIABLE" == "$BLANK_STRING" ]]; then

        if [ -z "$DEFAULT" ]; then
            error "You should specify default variable"
        else
            VARIABLE="$DEFAULT"
        fi
    fi

   return "$VARIABLE"
}

# Set default variables if needed.

# This password is for testing and it is equivalent to `devpass`.
# It is generated from (Note: It is fully deterministic, yet the random salt
# generated by the script ensures that the resulting hash is always unique.):
# https://github.com/bitcoin/bitcoin/blob/master/share/rpcauth/rpcauth.py
DEFAULT_PASSWORD='22d3dd348a42d7f040487887b0ea6cc7$79ce831819539c78537884f85b65a09e15b079d79eb8f99447ea9b0a58fa66a6'

RPCAUTH=$(set_default "$RPCAUTH" "devuser:$DEFAULT_PASSWORD")
NETWORK=$(set_default "$NETWORK" "regtest")
DEBUG=$(set_default "$BITCOIND_DEBUG" "1")

PARAMS=""
if [ "$NETWORK" != "mainnet" ]; then
   PARAMS="-$NETWORK"
fi

PARAMS=$(echo $PARAMS \
    "-debug"="$DEBUG" \
    "-rpcauth"="$RPCAUTH" \
    "-datadir"="/data" \
    "-debuglogfile"="/data/debug.log" \
    "-rpcbind"="0.0.0.0" \
    "-rpcallowip"="0.0.0.0/0" \
    "-zmqpubrawblock"="tcp://0.0.0.0:28332" \
    "-zmqpubrawtx"="tcp://0.0.0.0:28333" \
    "-txindex"
)

# Add user parameters to the command.
PARAMS="$PARAMS $@"

# Print command and start bitcoin node.
echo "Command: bitcoind $PARAMS"
exec bitcoind $PARAMS
