#!/bin/bash

CHAIN=
ABEC_RPC_PORT=
RPC_PORT=
ACCOUNT=
PUB_PASS=

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

exit_abnormal() {
  usage
  exit 1
}

while getopts "c:p:r:a:y:" opts; do
  case "${opts}" in
    c)
      CHAIN=${OPTARG}
      ;;
    p)
      ABEC_RPC_PORT=${OPTARG}
      ;;
    r)
      RPC_PORT=${OPTARG}
      ;;
    a)
      ACCOUNT=${OPTARG}
      ;;
    y)
      PUB_PASS=${OPTARG}
      ;;
    *)
      exit_abnormal
      ;;
  esac
done
shift $((OPTIND-1))

if [[ -z "$CHAIN" || -z "$ACCOUNT" || -z "$PUB_PASS" ]]; then
  exit_abnormal
fi

if [[ "$CHAIN" == "mainnet" ]]; then
  ABEC_RPC_PORT=${ABEC_RPC_PORT:-"8677"}
  RPC_PORT=${RPC_PORT:-"8675"}
else
  ABEC_RPC_PORT=${ABEC_RPC_PORT:-"18677"}
  RPC_PORT=${RPC_PORT:-"18675"}
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=$ABEWALLET_RELEASE_HOME
PROG="$RELEASE_DIR/abewallet"
LIB_DIR="$RELEASE_DIR/lib"
WALLET_DATA_DIR="$USER_DATA_DIR/Abewallet/$ACCOUNT"

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

CHAIN_OPT=""
if [[ "$CHAIN" == "testnet" ]]; then
  CHAIN_OPT="--testnet"
elif [[ "$CHAIN" == "simnet" ]]; then
  CHAIN_OPT="--simnet"
fi

# Check abewallet.conf is exist, if not, create one
ABEWALLET_CONF="$WALLET_DATA_DIR/abewallet.conf"
if [[ ! -f $ABEWALLET_CONF ]]; then
  touch $ABEWALLET_CONF
fi

exec "$PROG" \
  --appdata="$WALLET_DATA_DIR" \
  --logdir="$WALLET_DATA_DIR" \
  --noclienttls --noservertls \
  --abecrpcuser="localuser" --abecrpcpass="localpass" \
  --rpcuser="localuser" --rpcpass="localpass" \
  --walletpass="$PUB_PASS" \
  --rpclisten=127.0.0.1:${RPC_PORT} \
  --rpcconnect=127.0.0.1:${ABEC_RPC_PORT} \
  $CHAIN_OPT
