#!/bin/bash

CHAIN=mainnet

usage() {
  cat <<EOF 1>&2
Usage: $0 [-c CHAIN(mainnet|testnet|simnet)] [-p NODE_PORT] [-r RPC_PORT]
EOF
}

exit_abnormal() {
  usage
  exit 1
}

while getopts "c:p:r:" opts; do
  case "${opts}" in
    c)
      CHAIN=${OPTARG}
      if [[ "$CHAIN" != "mainnet" && "$CHAIN" != "testnet" && "$CHAIN" != "simnet" ]]; then
        exit_abnormal
      fi
      ;;
    p)
      NODE_PORT=${OPTARG}
      ;;
    r)
      RPC_PORT=${OPTARG}
      ;;
    *)
      exit_abnormal
      ;;
  esac
done
shift $((OPTIND-1))

if [[ "$CHAIN" == "mainnet" ]]; then
  NODE_PORT=${NODE_PORT:-"8676"}
  RPC_PORT=${RPC_PORT:-"8677"}
elif [[ "$CHAIN" == "testnet" ]]; then
  NODE_PORT=${NODE_PORT:-"18676"}
  RPC_PORT=${RPC_PORT:-"18677"}
else
  NODE_PORT=${NODE_PORT:-"18888"}
  RPC_PORT=${RPC_PORT:-"18889"}
fi

if [[ "$OSTYPE" == *"darwin"* ]]; then
  USER_DATA_DIR="$HOME/Library/Application Support/Abelian Wallet"
elif [[ "$OSTYPE" == *"linux"* ]]; then
  USER_DATA_DIR="$HOME/.config/Abelian Wallet"
else
  >&2 echo "ERROR: Unknown platform ($OSTYPE)."
  exit 1;
fi

SCRIPT=$(perl -e "use Cwd qw(abs_path);print abs_path('$0'),\"\n\";")
PROG_DIR="$(dirname "$SCRIPT")"
PROG="$PROG_DIR/abec"
LIB_DIR="$PROG_DIR/lib"
DATA_DIR="$USER_DATA_DIR/Abec"
WORK_DIR="$DATA_DIR"

CHAIN_OPTS=""
if [[ "$CHAIN" == "testnet" ]]; then
  CHAIN_OPTS="--testnet --addpeer=ec2-34-227-111-24.compute-1.amazonaws.com:18666"
elif [[ "$CHAIN" == "simnet" ]]; then
  CHAIN_OPTS="--simnet --addpeer=abec-service-simnet-0.abelos.io:18888 --addpeer=abec-service-simnet-1.abelos.io:18888 --addpeer=abec-service-simnet-2.abelos.io:18888"
fi

if [[ "$OSTYPE" == *"darwin"* ]]; then
  export DYLD_LIBRARY_PATH="$LIB_DIR"
elif [[ "$OSTYPE" == *"linux"* ]]; then
  export LD_LIBRARY_PATH="$LIB_DIR"
else
  >&2 echo "ERROR: Unknown platform ($OSTYPE)."
  exit 1;
fi

exec "$PROG" \
  --datadir="$DATA_DIR" \
  --logdir="$DATA_DIR/logs" \
  --notls --rpcuser="localuser" --rpcpass="localpass" \
  --listen=0.0.0.0:$NODE_PORT \
  --rpclisten=127.0.0.1:$RPC_PORT \
  --txindex \
  $CHAIN_OPTS
