#!/bin/bash

CHAIN=mainnet

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

exit_abnormal() {
  usage
  exit 1
}

while getopts "c:p:r:a:w:" 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}
      ;;
    a)
      ADD_CHECK_POINT=${OPTARG}
      ;;
    w)
      export ABEC_MAX_RESERVED_WITNESS=${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 [[ -n "$ABELWALLET_HOME" && "$ABELWALLET_HOME" = /* ]]; then
  USER_DATA_DIR="$ABELWALLET_HOME"
elif [[ "$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\";")
SCRIPT_DIR="$(dirname "$SCRIPT")"
RELEASE_DIR=$ABEC_RELEASE_HOME
PROG="$RELEASE_DIR/abec"
LIB_DIR="$RELEASE_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 [[ ! -z "$ADD_CHECK_POINT" ]]; then
  CHAIN_OPTS="$CHAIN_OPTS --addcheckpoint=$ADD_CHECK_POINT"
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

export ABEC_DO_NOT_ASK_FOR_NODE_TYPE_CHANGE=true

# Check abec.conf is exist, if not, create one
if [[ "$OSTYPE" == *"darwin"* ]]; then
  ABEC_DIR="$HOME/Library/Application Support/Abec"
elif [[ "$OSTYPE" == *"linux"* ]]; then
  ABEC_DIR="$HOME/.abec"
fi
if [[ ! -d "$ABEC_DIR" || ! -f "$ABEC_DIR/abec.conf" ]]; then
  mkdir -p "$ABEC_DIR" && touch "$ABEC_DIR/abec.conf"
fi

exec "$PROG" \
  --nodetype=normalnode \
  --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
