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

cd "$(dirname "$0")"

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

set -a
source .env
set +a

POOL_DB_NAME="${POOL_DB_NAME:-vexonpool}"
POOL_DB_USER="${POOL_DB_USER:-vexonpool}"
POOL_DB_PASSWORD="${POOL_DB_PASSWORD:-}"
VEX_BLOCK_SUBMIT_DIFF="${VEX_BLOCK_SUBMIT_DIFF:-503382015}"
VEX_ADDRESS="${VEX_ADDRESS:-}"
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:-}"
VEX_P2P_PORT="${VEX_P2P_PORT:-18555}"
VEX_RPC_PORT="${VEX_RPC_PORT:-18556}"
VEX_WALLET_RPC_PORT="${VEX_WALLET_RPC_PORT:-18557}"
VEX_MIN_PAYOUT="${VEX_MIN_PAYOUT:-0.001}"
VEX_EARNINGS_CLEAR_DELAY="${VEX_EARNINGS_CLEAR_DELAY:-0}"
VEX_MATURE_BLOCKS="${VEX_MATURE_BLOCKS:-100}"
VEX_TXFEE="${VEX_TXFEE:-0}"
VEX_PAYOUT_HOUR="${VEX_PAYOUT_HOUR:-8}"
VEX_PAYOUT_MINUTE="${VEX_PAYOUT_MINUTE:-0}"
VEX_PAYOUT_TIMEZONE="${VEX_PAYOUT_TIMEZONE:-Asia/Shanghai}"
VEX_PAYOUT_SCHEDULE_LABEL="${VEX_PAYOUT_SCHEDULE_LABEL:-Daily at 08:00 CST}"
VEX_PAYOUT_NOTE="${VEX_PAYOUT_NOTE:-Balances above the minimum are paid after block maturity.}"
VEX_CORE_REPO="${VEX_CORE_REPO:-https://github.com/vexonexchange-sudo/vexon-core.git}"
VEX_WALLET_REPO="${VEX_WALLET_REPO:-https://github.com/vexonexchange-sudo/vexon-wallet.git}"
VEX_STRATUM_REPO="${VEX_STRATUM_REPO:-https://github.com/vexonexchange-sudo/vexon-stratum.git}"
VEX_CORE_REF="${VEX_CORE_REF:-main}"
VEX_WALLET_REF="${VEX_WALLET_REF:-main}"
VEX_STRATUM_REF="${VEX_STRATUM_REF:-main}"
VEX_LOCAL_RELEASE_DIR="${VEX_LOCAL_RELEASE_DIR:-}"
VEX_LOCAL_STRATUM_DIR="${VEX_LOCAL_STRATUM_DIR:-}"
VEX_START_WALLET="${VEX_START_WALLET:-0}"
STRATUM_DB_USER="${STRATUM_DB_USER:-vexonstratum}"
STRATUM_PORT="${STRATUM_PORT:-4499}"
VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_BIN_DIR="${VEX_BIN_DIR:-$VEX_POOL_ROOT/bin}"
VEX_WEB_DIR="${VEX_WEB_DIR:-$VEX_POOL_ROOT/web}"
VEX_DOCS_DIR="${VEX_DOCS_DIR:-$VEX_POOL_ROOT/docs}"
VEX_LOG_DIR="${VEX_LOG_DIR:-$VEX_POOL_ROOT/log}"
VEX_SOURCE_DIR="${VEX_SOURCE_DIR:-$VEX_POOL_ROOT/src}"
VEX_STRATUM_DIR="${VEX_STRATUM_DIR:-$VEX_POOL_ROOT/stratum}"
VEX_STRATUM_CONFIG_DIR="${VEX_STRATUM_CONFIG_DIR:-$VEX_POOL_ROOT/stratum-config}"
VEX_NODE_APPDATA="${VEX_NODE_APPDATA:-/root/.vexond}"
VEX_WALLET_APPDATA="${VEX_WALLET_APPDATA:-/root/.vexonwallet}"
VEX_ENABLE_LOCAL_PEER="${VEX_ENABLE_LOCAL_PEER:-1}"
VEX_PEER_APPDATA="${VEX_PEER_APPDATA:-/root/.vexond-peer}"
VEX_PEER_P2P_PORT="${VEX_PEER_P2P_PORT:-18565}"
VEX_PEER_RPC_PORT="${VEX_PEER_RPC_PORT:-18566}"
VEX_NODE_SCREEN="${VEX_NODE_SCREEN:-Vexon_Node}"
VEX_WALLET_SCREEN="${VEX_WALLET_SCREEN:-Vexon_Wallet}"
VEX_STRATUM_SCREEN="${VEX_STRATUM_SCREEN:-Vexon_Stratum}"
VEX_PEER_SCREEN="${VEX_PEER_SCREEN:-Vexon_Node_Peer}"
VEX_CONFIGURE_NGINX="${VEX_CONFIGURE_NGINX:-0}"
VEX_BACKEND_CAN_STOP_NGINX="${VEX_BACKEND_CAN_STOP_NGINX:-0}"
VEX_NGINX_CONF_NAME="${VEX_NGINX_CONF_NAME:-vexon-pool.conf}"
VEX_DOCS_DOMAIN="${VEX_DOCS_DOMAIN:-docs.vexonus.com}"
VEX_DOCS_NGINX_CONF_NAME="${VEX_DOCS_NGINX_CONF_NAME:-vexon-docs.conf}"

if [[ -z "$POOL_DB_PASSWORD" ]]; then
  echo "Missing POOL_DB_PASSWORD in .env" >&2
  exit 1
fi

for required in VEX_ADDRESS VEX_RPC_USER VEX_RPC_PASSWORD VEX_WALLET_RPC_USER VEX_WALLET_RPC_PASSWORD; do
  if [[ -z "${!required:-}" ]]; then
    echo "Missing $required in .env" >&2
    exit 1
  fi
done

require_root() {
  if [[ "$(id -u)" != "0" ]]; then
    echo "Run as root: sudo bash install.sh" >&2
    exit 1
  fi
}

clone_or_update_repo() {
  local repo="$1"
  local dir="$2"
  local ref="$3"

  if [[ ! -d "$dir/.git" ]]; then
    rm -rf "$dir"
    git clone "$repo" "$dir"
  fi

  (
    cd "$dir"
    git fetch --all --tags
    git checkout "$ref"
    git reset --hard "origin/$ref" 2>/dev/null || git reset --hard "$ref"
  )
}

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

  until "$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; do
    if (( elapsed >= timeout )); then
      echo "Timed out waiting for Vexon node RPC on 127.0.0.1:${VEX_RPC_PORT}" >&2
      tail -80 "$VEX_NODE_APPDATA/logs/mainnet/vexond.log" 2>/dev/null || true
      return 1
    fi
    sleep 1
    elapsed=$((elapsed + 1))
  done
}

show_stratum_diagnostics() {
  echo
  echo "== Stratum diagnostics =="
  screen -ls || true
  echo
  ps -ef | grep -E 'VexonStratum|Vexon_Stratum|run.sh vexon' | grep -v grep || true
  echo
  ss -lntp | grep -E ":${STRATUM_PORT}\\b" || true
  echo
  tail -80 "$VEX_STRATUM_CONFIG_DIR/vexon.log" 2>/dev/null || true
}

wait_for_stratum_port() {
  local timeout="${1:-30}"
  local elapsed=0

  while (( elapsed < timeout )); do
    if ss -lnt | awk '{print $4}' | grep -Eq "[:.]${STRATUM_PORT}$"; then
      echo "Stratum is listening on $STRATUM_PORT"
      return 0
    fi
    sleep 1
    elapsed=$((elapsed + 1))
  done

  show_stratum_diagnostics
  echo "Timed out waiting for Stratum on 0.0.0.0:${STRATUM_PORT}" >&2
  return 1
}

wait_for_wallet_rpc() {
  local timeout="${1:-60}"
  local elapsed=0

  until "$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 >/dev/null 2>&1; do
    if (( elapsed >= timeout )); then
      echo "Timed out waiting for Vexon wallet RPC on 127.0.0.1:${VEX_WALLET_RPC_PORT}" >&2
      tail -100 "$VEX_WALLET_APPDATA/logs/mainnet/vexonwallet.log" 2>/dev/null || true
      return 1
    fi
    sleep 1
    elapsed=$((elapsed + 1))
  done

  echo "Wallet RPC is responding on $VEX_WALLET_RPC_PORT"
}

render_template() {
  local src="$1"
  local dst="$2"
  cp "$src" "$dst"
  local vars=(
    POOL_DOMAIN VEX_DOCS_DOMAIN POOL_SITE_NAME POOL_ADMIN_EMAIL POOL_ADMIN_IP
    MYSQL_ROOT_PASSWORD POOL_DB_NAME POOL_DB_USER POOL_DB_PASSWORD
    STRATUM_DB_USER STRATUM_DB_PASSWORD STRATUM_TCP_PASSWORD STRATUM_PORT
    STRATUM_DIFFICULTY VEX_BLOCK_SUBMIT_DIFF VEX_ADDRESS VEX_RPC_USER
    VEX_RPC_PASSWORD VEX_WALLET_RPC_USER VEX_WALLET_RPC_PASSWORD
    VEX_WALLET_PASSPHRASE VEX_P2P_PORT VEX_RPC_PORT VEX_WALLET_RPC_PORT VEX_MIN_PAYOUT
    VEX_EARNINGS_CLEAR_DELAY VEX_PAYOUT_HOUR VEX_PAYOUT_MINUTE VEX_PAYOUT_TIMEZONE
    VEX_PAYOUT_SCHEDULE_LABEL VEX_PAYOUT_NOTE
    VEX_POOL_ROOT VEX_BIN_DIR VEX_WEB_DIR VEX_DOCS_DIR VEX_LOG_DIR VEX_SOURCE_DIR
    VEX_STRATUM_DIR VEX_STRATUM_CONFIG_DIR VEX_NODE_APPDATA VEX_WALLET_APPDATA
    VEX_ENABLE_LOCAL_PEER VEX_PEER_APPDATA VEX_PEER_P2P_PORT VEX_PEER_RPC_PORT
    VEX_BACKEND_CAN_STOP_NGINX
  )
  local name value escaped
  for name in "${vars[@]}"; do
    value="${!name:-}"
    escaped="$(printf '%s' "$value" | sed -e 's/[\/&]/\\&/g')"
    sed -i "s/{{$name}}/$escaped/g" "$dst"
  done
}

install_packages() {
  apt-get update
  local packages=(
    build-essential git curl screen rsync ca-certificates pkg-config \
    mariadb-server mariadb-client \
    php-cli php-mysql php-curl php-gd php-mbstring php-xml php-zip \
    default-libmysqlclient-dev libcurl4-openssl-dev libgmp-dev libssl-dev zlib1g-dev golang-go
  )
  if [[ "$VEX_CONFIGURE_NGINX" == "1" ]]; then
    packages+=(nginx php-fpm)
  fi
  DEBIAN_FRONTEND=noninteractive apt-get install -y "${packages[@]}"
}

install_web() {
  mkdir -p "$VEX_WEB_DIR" "$VEX_DOCS_DIR" "$VEX_BIN_DIR" "$VEX_LOG_DIR" /etc/vexon-pool /root/backup
  rsync -a --delete files/var-web/ "$VEX_WEB_DIR/"
  rsync -a --delete files/docs-site/ "$VEX_DOCS_DIR/"
  mkdir -p "$VEX_WEB_DIR/vexon/runtime/cookies" "$VEX_WEB_DIR/assets"
  chmod +x "$VEX_WEB_DIR/main.sh" "$VEX_WEB_DIR/loop2.sh" "$VEX_WEB_DIR/blocks.sh" || true
  render_template templates/serverconfig.php.tmpl "$VEX_WEB_DIR/serverconfig.php"
  render_template templates/keys.php.tmpl /etc/vexon-pool/keys.php
  chown -R www-data:www-data "$VEX_WEB_DIR" 2>/dev/null || true
  chown -R www-data:www-data "$VEX_DOCS_DIR" 2>/dev/null || true
  chmod -R 775 "$VEX_WEB_DIR/vexon/runtime" "$VEX_WEB_DIR/assets" 2>/dev/null || true
}

configure_nginx_php() {
  if [[ "$VEX_CONFIGURE_NGINX" != "1" ]]; then
    echo "Skipping system nginx configuration because VEX_CONFIGURE_NGINX=$VEX_CONFIGURE_NGINX"
    return
  fi
  local php_sock
  php_sock="$(find /run/php -name 'php*-fpm.sock' | head -1 || true)"
  if [[ -z "$php_sock" ]]; then
    systemctl restart php*-fpm || true
    php_sock="$(find /run/php -name 'php*-fpm.sock' | head -1 || true)"
  fi
  render_template templates/nginx-vexon-pool.conf.tmpl "/etc/nginx/sites-available/$VEX_NGINX_CONF_NAME"
  render_template templates/nginx-vexon-docs.conf.tmpl "/etc/nginx/sites-available/$VEX_DOCS_NGINX_CONF_NAME"
  if [[ -n "$php_sock" ]]; then
    sed -i "s#unix:/run/php/php-fpm.sock#unix:$php_sock#g" "/etc/nginx/sites-available/$VEX_NGINX_CONF_NAME"
  fi
  ln -sf "/etc/nginx/sites-available/$VEX_NGINX_CONF_NAME" "/etc/nginx/sites-enabled/$VEX_NGINX_CONF_NAME"
  ln -sf "/etc/nginx/sites-available/$VEX_DOCS_NGINX_CONF_NAME" "/etc/nginx/sites-enabled/$VEX_DOCS_NGINX_CONF_NAME"
  nginx -t
  systemctl enable nginx
  systemctl restart nginx
}

configure_mysql() {
  systemctl enable mariadb
  systemctl start mariadb

  mysql -uroot <<SQL
CREATE DATABASE IF NOT EXISTS \`${POOL_DB_NAME}\` CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER IF NOT EXISTS '${POOL_DB_USER}'@'localhost' IDENTIFIED BY '${POOL_DB_PASSWORD}';
CREATE USER IF NOT EXISTS '${STRATUM_DB_USER}'@'localhost' IDENTIFIED BY '${STRATUM_DB_PASSWORD}';
GRANT ALL PRIVILEGES ON \`${POOL_DB_NAME}\`.* TO '${POOL_DB_USER}'@'localhost';
GRANT ALL PRIVILEGES ON \`${POOL_DB_NAME}\`.* TO '${STRATUM_DB_USER}'@'localhost';
FLUSH PRIVILEGES;
SQL

  if ! mysql -uroot "$POOL_DB_NAME" -e "SHOW TABLES LIKE 'coins';" | grep -q coins; then
    echo "Importing files/sql/2016-04-03-vexon.sql.gz"
    gzip -dc files/sql/2016-04-03-vexon.sql.gz | mysql -uroot "$POOL_DB_NAME"

    for f in files/sql/*.sql; do
      [[ -e "$f" ]] || continue
      case "$(basename "$f")" in
        2015-*|2016-02-*|2016-03-*|2016-04-03-*) continue ;;
      esac
      echo "Importing $f"
      mysql -uroot "$POOL_DB_NAME" < "$f"
    done
  fi

  mysql -uroot "$POOL_DB_NAME" <<SQL
INSERT INTO coins
  (name, symbol, symbol2, algo, rpcencoding, master_wallet, image, enable, auto_ready, visible, installed, reward, price, txfee,
   difficulty, block_time, mature_blocks, payout_min, rpchost, rpcport, rpcuser, rpcpasswd, hassubmitblock, usememorypool, rpccurl, rpcssl, account)
SELECT
  'Vexon', 'VEX', '', 'decred', 'DCR', '${VEX_ADDRESS}', '/vexon/ui/images/vexon-logo.png', 1, 1, 1, 1, 50, 0, ${VEX_TXFEE},
  ${VEX_BLOCK_SUBMIT_DIFF}, 300, ${VEX_MATURE_BLOCKS}, ${VEX_MIN_PAYOUT}, '127.0.0.1', ${VEX_RPC_PORT}, '${VEX_RPC_USER}', '${VEX_RPC_PASSWORD}', 1, 1, 1, 0, ''
FROM (SELECT 1) AS vex_seed
WHERE NOT EXISTS (SELECT 1 FROM coins WHERE symbol='VEX');
UPDATE coins SET
  name='Vexon',
  symbol='VEX',
  symbol2='',
  algo='decred',
  rpcencoding='DCR',
  master_wallet='${VEX_ADDRESS}',
  image='/vexon/ui/images/vexon-logo.png',
  enable=1,
  auto_ready=1,
  visible=1,
  installed=1,
  reward=50,
  txfee=${VEX_TXFEE},
  block_time=300,
  mature_blocks=${VEX_MATURE_BLOCKS},
  payout_min=${VEX_MIN_PAYOUT},
  difficulty=${VEX_BLOCK_SUBMIT_DIFF},
  rpchost='127.0.0.1',
  rpcport=${VEX_RPC_PORT},
  rpcuser='${VEX_RPC_USER}',
  rpcpasswd='${VEX_RPC_PASSWORD}',
  hassubmitblock=1,
  usememorypool=1,
  rpccurl=1,
  rpcssl=0,
  rpccert=''
WHERE symbol='VEX';
SQL

  if mysql -uroot "$POOL_DB_NAME" -Nse "SHOW COLUMNS FROM coins LIKE 'hasgetinfo'" | grep -q '^hasgetinfo'; then
    mysql -uroot "$POOL_DB_NAME" -e "UPDATE coins SET hasgetinfo=0 WHERE symbol='VEX';"
  fi
}

restore_pool_backup() {
  local backup="${POOL_BACKUP_TAR:-}"
  [[ -n "$backup" ]] || return 0
  [[ -f "$backup" ]] || { echo "POOL_BACKUP_TAR not found: $backup" >&2; exit 1; }

  local restore_dir="/root/vexon-pool-restore"
  rm -rf "$restore_dir"
  mkdir -p "$restore_dir"
  tar -xzf "$backup" -C "$restore_dir"

  if [[ -f "$restore_dir/mysql/vexonpool.sql.gz" ]]; then
    gzip -dc "$restore_dir/mysql/vexonpool.sql.gz" | mysql -uroot "$POOL_DB_NAME"
  fi

	  if [[ -d "$restore_dir/root-dot-vexond" ]]; then
	    rsync -a --delete "$restore_dir/root-dot-vexond/" "$VEX_NODE_APPDATA/"
	  fi

	  if [[ -d "$restore_dir/root-dot-vexonwallet" ]]; then
	    rsync -a --delete "$restore_dir/root-dot-vexonwallet/" "$VEX_WALLET_APPDATA/"
	  fi

	  if [[ -f "$restore_dir/var-stratum-config/vexon.conf" ]]; then
	    mkdir -p "$VEX_STRATUM_CONFIG_DIR"
	    cp -av "$restore_dir/var-stratum-config/vexon.conf" "$VEX_STRATUM_CONFIG_DIR/vexon.conf"
	  fi

	  if [[ -f "$restore_dir/var-web/serverconfig.php" ]]; then
	    cp -av "$restore_dir/var-web/serverconfig.php" "$VEX_WEB_DIR/serverconfig.php"
	  fi

  if [[ -f "$restore_dir/etc-vexon-pool/keys.php" ]]; then
    mkdir -p /etc/vexon-pool
    cp -av "$restore_dir/etc-vexon-pool/keys.php" /etc/vexon-pool/keys.php
  fi
}

install_node_wallet() {
  mkdir -p "$VEX_BIN_DIR"
  if [[ -n "$VEX_LOCAL_RELEASE_DIR" ]]; then
    test -x "$VEX_LOCAL_RELEASE_DIR/bin/vexond"
    test -x "$VEX_LOCAL_RELEASE_DIR/bin/vexonctl"
    test -x "$VEX_LOCAL_RELEASE_DIR/bin/vexonwallet"
    install -m 0755 "$VEX_LOCAL_RELEASE_DIR/bin/vexond" "$VEX_BIN_DIR/vexond"
    install -m 0755 "$VEX_LOCAL_RELEASE_DIR/bin/vexonctl" "$VEX_BIN_DIR/vexonctl"
    install -m 0755 "$VEX_LOCAL_RELEASE_DIR/bin/vexonwallet" "$VEX_BIN_DIR/vexonwallet"
    return
  fi

  if [[ "${VEX_SKIP_NODE_BUILD:-0}" == "1" ]]; then
    test -x "$VEX_BIN_DIR/vexond"
    test -x "$VEX_BIN_DIR/vexonwallet"
    test -x "$VEX_BIN_DIR/vexonctl"
    return
  fi

  mkdir -p "$VEX_SOURCE_DIR"
  clone_or_update_repo "$VEX_CORE_REPO" "$VEX_SOURCE_DIR/vexon-core" "$VEX_CORE_REF"
  clone_or_update_repo "$VEX_WALLET_REPO" "$VEX_SOURCE_DIR/vexon-wallet" "$VEX_WALLET_REF"

  if [[ -x "$VEX_SOURCE_DIR/vexon-core/scripts/build-vexon-node.sh" ]]; then
    "$VEX_SOURCE_DIR/vexon-core/scripts/build-vexon-node.sh" "$VEX_BIN_DIR"
  else
    (cd "$VEX_SOURCE_DIR/vexon-core" && go build -o "$VEX_BIN_DIR/vexond" .)
    (cd "$VEX_SOURCE_DIR/vexon-core" && go build -o "$VEX_BIN_DIR/vexonctl" ./cmd/vexonctl)
  fi

  if [[ -x "$VEX_SOURCE_DIR/vexon-wallet/scripts/build-vexon-wallet.sh" ]]; then
    "$VEX_SOURCE_DIR/vexon-wallet/scripts/build-vexon-wallet.sh" "$VEX_BIN_DIR"
  else
    (cd "$VEX_SOURCE_DIR/vexon-wallet" && GO111MODULE=auto go build -o "$VEX_BIN_DIR/vexonwallet" .)
  fi
}

configure_node_wallet() {
  mkdir -p "$VEX_NODE_APPDATA" "$VEX_WALLET_APPDATA"
  render_template templates/vexond.conf.tmpl "$VEX_NODE_APPDATA/vexond.conf"
  render_template templates/vexonwallet.conf.tmpl "$VEX_WALLET_APPDATA/vexonwallet.conf"
  chmod 600 "$VEX_NODE_APPDATA/vexond.conf" "$VEX_WALLET_APPDATA/vexonwallet.conf"

  if [[ "$VEX_ENABLE_LOCAL_PEER" == "1" ]]; then
    mkdir -p "$VEX_PEER_APPDATA"
    render_template templates/vexond-peer.conf.tmpl "$VEX_PEER_APPDATA/vexond.conf"
    chmod 600 "$VEX_PEER_APPDATA/vexond.conf"
  fi
}

install_stratum() {
  mkdir -p "$VEX_STRATUM_DIR" "$VEX_STRATUM_CONFIG_DIR" "$VEX_SOURCE_DIR"
  if [[ -n "$VEX_LOCAL_STRATUM_DIR" ]]; then
    rm -rf "$VEX_SOURCE_DIR/vexon-stratum"
    rsync -a --delete "$VEX_LOCAL_STRATUM_DIR/" "$VEX_SOURCE_DIR/vexon-stratum/"
  else
    clone_or_update_repo "$VEX_STRATUM_REPO" "$VEX_SOURCE_DIR/vexon-stratum" "$VEX_STRATUM_REF"
  fi
  render_template templates/vexon-stratum.conf.tmpl "$VEX_STRATUM_CONFIG_DIR/vexon.conf"
  cat > "$VEX_STRATUM_CONFIG_DIR/run.sh" <<EOS
#!/usr/bin/env bash
cd "$VEX_STRATUM_DIR"
while true; do ./VexonStratum "$VEX_STRATUM_CONFIG_DIR/\$1"; sleep 2; done
EOS
  chmod +x "$VEX_STRATUM_CONFIG_DIR/run.sh"
  (
    cd "$VEX_SOURCE_DIR/vexon-stratum"
    STRATUM_DIR="$VEX_STRATUM_DIR" \
      STRATUM_CONFIG_DIR="$VEX_STRATUM_CONFIG_DIR" \
      STRATUM_CONFIG_NAME=vexon \
      SCREEN_NAME="$VEX_STRATUM_SCREEN" \
      bash install-vexon-stratum.sh
  )
}

start_services() {
  screen -S "$VEX_NODE_SCREEN" -X quit >/dev/null 2>&1 || true
  screen -S "$VEX_PEER_SCREEN" -X quit >/dev/null 2>&1 || true
  screen -S "$VEX_WALLET_SCREEN" -X quit >/dev/null 2>&1 || true
  screen -S "$VEX_STRATUM_SCREEN" -X quit >/dev/null 2>&1 || true
  screen -S vexon-pool-main -X quit >/dev/null 2>&1 || true
  screen -S vexon-pool-loop2 -X quit >/dev/null 2>&1 || true
  screen -S vexon-pool-blocks -X quit >/dev/null 2>&1 || true
  sleep 2

  screen -dmS "$VEX_NODE_SCREEN" "$VEX_BIN_DIR/vexond" --appdata="$VEX_NODE_APPDATA" --configfile="$VEX_NODE_APPDATA/vexond.conf"
  wait_for_node_rpc 60
  if [[ "$VEX_ENABLE_LOCAL_PEER" == "1" ]]; then
    screen -dmS "$VEX_PEER_SCREEN" "$VEX_BIN_DIR/vexond" --appdata="$VEX_PEER_APPDATA" --configfile="$VEX_PEER_APPDATA/vexond.conf"
    sleep 5
    "$VEX_BIN_DIR/vexonctl" --notls --rpcserver "127.0.0.1:${VEX_RPC_PORT}" -u "$VEX_RPC_USER" -P "$VEX_RPC_PASSWORD" addnode "127.0.0.1:${VEX_PEER_P2P_PORT}" add >/dev/null 2>&1 || true
  fi
  if [[ "$VEX_START_WALLET" == "1" ]]; then
    if [[ -z "$VEX_WALLET_PASSPHRASE" ]]; then
      echo "VEX_START_WALLET=1 requires VEX_WALLET_PASSPHRASE in .env" >&2
      return 1
    fi
    if [[ -z "$VEX_WALLET_RPC_USER" || -z "$VEX_WALLET_RPC_PASSWORD" ]]; then
      echo "VEX_START_WALLET=1 requires VEX_WALLET_RPC_USER and VEX_WALLET_RPC_PASSWORD in .env" >&2
      return 1
    fi
    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
    wait_for_wallet_rpc 60
  else
    echo "Skipping $VEX_WALLET_SCREEN screen because VEX_START_WALLET=$VEX_START_WALLET"
  fi

  cd "$VEX_STRATUM_CONFIG_DIR"
  screen -dmS "$VEX_STRATUM_SCREEN" ./run.sh vexon
  wait_for_stratum_port 30

  cd "$VEX_WEB_DIR"
  screen -dmS vexon-pool-main ./main.sh
  screen -dmS vexon-pool-loop2 ./loop2.sh
  screen -dmS vexon-pool-blocks ./blocks.sh
}

print_status() {
  screen -ls || true
  ps -ef | grep -E 'vexond|vexonwallet|VexonStratum|main.sh|loop2.sh|blocks.sh' | grep -v grep || true
  ss -lntp | grep -E "${STRATUM_PORT}|${VEX_P2P_PORT}|${VEX_RPC_PORT}|${VEX_WALLET_RPC_PORT}|:80" || true
}

require_root
install_packages
install_web
configure_nginx_php
configure_mysql
install_node_wallet
configure_node_wallet
install_stratum
restore_pool_backup
start_services
print_status

echo "Vexon Pool install finished."
