#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

if [[ ! -f .env ]]; then
  echo "Missing .env. Copy .env.example to .env and edit it first." >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
source .env
set +a

VEX_START_WALLET="${VEX_START_WALLET:-0}"
VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_BIN_DIR="${VEX_BIN_DIR:-$VEX_POOL_ROOT/bin}"
VEX_NODE_APPDATA="${VEX_NODE_APPDATA:-/root/.vexond}"
VEX_WALLET_APPDATA="${VEX_WALLET_APPDATA:-/root/.vexonwallet}"
VEX_RPC_PORT="${VEX_RPC_PORT:-18556}"
VEX_WALLET_RPC_PORT="${VEX_WALLET_RPC_PORT:-18557}"
VEX_RPC_USER="${VEX_RPC_USER:-}"
VEX_RPC_PASSWORD="${VEX_RPC_PASSWORD:-}"
VEX_WALLET_RPC_USER="${VEX_WALLET_RPC_USER:-}"
VEX_WALLET_RPC_PASSWORD="${VEX_WALLET_RPC_PASSWORD:-}"
VEX_WALLET_PASSPHRASE="${VEX_WALLET_PASSPHRASE:-}"

die() {
  printf '[FAIL] %s\n' "$1" >&2
  exit 1
}

wait_for_node_rpc() {
  local timeout="${1:-90}"
  local elapsed=0

  while (( elapsed < timeout )); do
    if "$VEX_BIN_DIR/vexonctl" \
      --notls \
      --rpcserver "127.0.0.1:${VEX_RPC_PORT}" \
      -u "$VEX_RPC_USER" \
      -P "$VEX_RPC_PASSWORD" \
      getblockcount >/dev/null 2>&1; then
      return 0
    fi
    sleep 1
    elapsed=$((elapsed + 1))
  done

  die "Vexon node RPC did not answer on 127.0.0.1:${VEX_RPC_PORT}"
}

[[ "$VEX_START_WALLET" == "1" ]] || die "VEX_START_WALLET must be 1 for wallet systemd service"
[[ -x "$VEX_BIN_DIR/vexonwallet" ]] || die "missing executable: $VEX_BIN_DIR/vexonwallet"
[[ -x "$VEX_BIN_DIR/vexonctl" ]] || die "missing executable: $VEX_BIN_DIR/vexonctl"
[[ -n "$VEX_RPC_USER" ]] || die "VEX_RPC_USER is not set"
[[ -n "$VEX_RPC_PASSWORD" ]] || die "VEX_RPC_PASSWORD is not set"
[[ -n "$VEX_WALLET_RPC_USER" ]] || die "VEX_WALLET_RPC_USER is not set"
[[ -n "$VEX_WALLET_RPC_PASSWORD" ]] || die "VEX_WALLET_RPC_PASSWORD is not set"
[[ -n "$VEX_WALLET_PASSPHRASE" ]] || die "VEX_WALLET_PASSPHRASE is not set"
[[ "$VEX_WALLET_PASSPHRASE" != *$'\n'* ]] || die "VEX_WALLET_PASSPHRASE must be a single line"
[[ -f "$VEX_WALLET_APPDATA/mainnet/wallet.db" ]] || die "wallet.db is missing under $VEX_WALLET_APPDATA/mainnet"

chmod 600 .env
install -d -m 700 "$VEX_WALLET_APPDATA"

cat > "$VEX_WALLET_APPDATA/vexonwallet.conf" <<EOF
noservertls=1
noclienttls=1
nogrpc=1
rpclisten=127.0.0.1:${VEX_WALLET_RPC_PORT}
username=${VEX_WALLET_RPC_USER}
password=${VEX_WALLET_RPC_PASSWORD}
pass=${VEX_WALLET_PASSPHRASE}
appdata=${VEX_WALLET_APPDATA}
rpcconnect=127.0.0.1:${VEX_RPC_PORT}
cafile=${VEX_NODE_APPDATA}/rpc.cert
EOF
chmod 600 "$VEX_WALLET_APPDATA/vexonwallet.conf"

wait_for_node_rpc 90

exec "$VEX_BIN_DIR/vexonwallet" \
  --configfile="$VEX_WALLET_APPDATA/vexonwallet.conf" \
  --appdata="$VEX_WALLET_APPDATA" \
  --rpcconnect="127.0.0.1:${VEX_RPC_PORT}" \
  --noclienttls \
  --noservertls
