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

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

if [[ -f .env ]]; then
  set -a
  # shellcheck source=/dev/null
  source .env
  set +a
fi

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_WALLET_SCREEN="${VEX_WALLET_SCREEN:-Vexon_Wallet}"
VEX_RPC_PORT="${VEX_RPC_PORT:-18556}"
VEX_WALLET_RPC_PORT="${VEX_WALLET_RPC_PORT:-18557}"
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; }
ok() { printf '[OK] %s\n' "$1"; }
warn() { printf '[WARN] %s\n' "$1"; }

require_file_mode() {
  if [[ -f .env ]]; then
    chmod 600 .env
    ok ".env permissions set to 600"
  fi
}

wallet_log() {
  tail -120 "$VEX_WALLET_APPDATA/logs/mainnet/vexonwallet.log" 2>/dev/null || true
}

wait_for_wallet_rpc() {
  local timeout="${1:-60}"
  local elapsed=0
  local err="/tmp/vexon-wallet-rpc.err.$$"

  while (( elapsed < timeout )); do
    if "$VEX_BIN_DIR/vexonctl" \
      --wallet \
      --notls \
      --rpcserver "127.0.0.1:${VEX_WALLET_RPC_PORT}" \
      -u "$VEX_WALLET_RPC_USER" \
      -P "$VEX_WALLET_RPC_PASSWORD" \
      getbalance >/tmp/vexon-wallet-balance.$$ 2>"$err"; then
      ok "wallet RPC getbalance: $(cat /tmp/vexon-wallet-balance.$$)"
      rm -f /tmp/vexon-wallet-balance.$$ "$err"
      return 0
    fi
    sleep 1
    elapsed=$((elapsed + 1))
  done

  printf '\n== wallet RPC error ==\n' >&2
  cat "$err" >&2 2>/dev/null || true
  rm -f /tmp/vexon-wallet-balance.$$ "$err"
  printf '\n== wallet log ==\n' >&2
  wallet_log >&2
  die "wallet RPC did not answer on 127.0.0.1:${VEX_WALLET_RPC_PORT}"
}

find_wallet_db() {
  find "$VEX_WALLET_APPDATA" -maxdepth 3 -type f -name wallet.db 2>/dev/null | head -1
}

[[ "$VEX_START_WALLET" == "1" ]] || die "Set VEX_START_WALLET=1 in .env before enabling automatic payouts"
[[ -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_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"

require_file_mode

wallet_db="$(find_wallet_db)"
if [[ -z "$wallet_db" ]]; then
  die "wallet.db was not found under $VEX_WALLET_APPDATA. Create or restore the payout wallet first."
fi
ok "wallet database found: $wallet_db"

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"
ok "wallet config rendered: $VEX_WALLET_APPDATA/vexonwallet.conf"

if ss -lnt | awk '{print $4}' | grep -Eq "[:.]${VEX_WALLET_RPC_PORT}$"; then
  warn "wallet RPC port ${VEX_WALLET_RPC_PORT} is already listening; restarting $VEX_WALLET_SCREEN"
fi

screen -S "$VEX_WALLET_SCREEN" -X quit >/dev/null 2>&1 || true
sleep 2
screen -dmS "$VEX_WALLET_SCREEN" "$VEX_BIN_DIR/vexonwallet" \
  --configfile="$VEX_WALLET_APPDATA/vexonwallet.conf" \
  --appdata="$VEX_WALLET_APPDATA" \
  --rpcconnect="127.0.0.1:${VEX_RPC_PORT}" \
  --noclienttls \
  --noservertls
ok "started $VEX_WALLET_SCREEN"

wait_for_wallet_rpc 60

if "$VEX_BIN_DIR/vexonctl" --wallet --notls --rpcserver "127.0.0.1:${VEX_WALLET_RPC_PORT}" \
  -u "$VEX_WALLET_RPC_USER" -P "$VEX_WALLET_RPC_PASSWORD" walletislocked >/tmp/vexon-wallet-locked.$$ 2>/dev/null; then
  ok "wallet lock state: $(cat /tmp/vexon-wallet-locked.$$)"
  rm -f /tmp/vexon-wallet-locked.$$
fi

ok "Vexon wallet RPC is ready for payout checks"
