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

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

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

POOL_DOMAIN="${POOL_DOMAIN:-pool.vexonus.com}"
VEX_DOCS_DOMAIN="${VEX_DOCS_DOMAIN:-docs.vexonus.com}"
POOL_SITE_NAME="${POOL_SITE_NAME:-Vexon Pool}"
POOL_ADMIN_EMAIL="${POOL_ADMIN_EMAIL:-admin@example.com}"
POOL_ADMIN_IP="${POOL_ADMIN_IP:-}"
MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-}"
POOL_DB_NAME="${POOL_DB_NAME:-vexonpool}"
POOL_DB_USER="${POOL_DB_USER:-vexonpool}"
POOL_DB_PASSWORD="${POOL_DB_PASSWORD:-}"
STRATUM_DB_USER="${STRATUM_DB_USER:-vexonstratum}"
STRATUM_DB_PASSWORD="${STRATUM_DB_PASSWORD:-}"
STRATUM_TCP_PASSWORD="${STRATUM_TCP_PASSWORD:-}"
STRATUM_PORT="${STRATUM_PORT:-4499}"
STRATUM_DIFFICULTY="${STRATUM_DIFFICULTY:-256}"
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_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_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_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_BACKEND_CAN_STOP_NGINX="${VEX_BACKEND_CAN_STOP_NGINX:-0}"
VEX_WEB_USER="${VEX_WEB_USER:-www-data}"
VEX_WEB_GROUP="${VEX_WEB_GROUP:-www-data}"

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

[[ -d files/var-web ]] || die "missing files/var-web"
[[ -d files/docs-site ]] || die "missing files/docs-site"
command -v rsync >/dev/null 2>&1 || die "rsync is required"

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_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
}

if [[ "$(id -u)" != "0" && ( ! -w "$(dirname "$VEX_WEB_DIR")" || ! -w "$(dirname "$VEX_DOCS_DIR")" ) ]]; then
  die "run as root on the server, or make the target directories writable"
fi

mkdir -p "$VEX_WEB_DIR" "$VEX_DOCS_DIR" "$VEX_LOG_DIR"

rsync -a files/var-web/ "$VEX_WEB_DIR/"
rsync -a files/docs-site/ "$VEX_DOCS_DIR/"

if [[ "$have_env" == "1" && -f templates/serverconfig.php.tmpl ]]; then
  render_template templates/serverconfig.php.tmpl "$VEX_WEB_DIR/serverconfig.php"
  ok "serverconfig.php rendered from .env"
else
  warn "missing .env or templates/serverconfig.php.tmpl; kept existing serverconfig.php"
fi

mkdir -p \
  "$VEX_WEB_DIR/assets" \
  "$VEX_WEB_DIR/vexon/runtime" \
  "$VEX_WEB_DIR/vexon/runtime/cookies"

touch "$VEX_LOG_DIR/debug.log" "$VEX_LOG_DIR/rental.log"

chmod +x \
  "$VEX_WEB_DIR/main.sh" \
  "$VEX_WEB_DIR/loop2.sh" \
  "$VEX_WEB_DIR/blocks.sh" \
  "$VEX_WEB_DIR/run.php" \
  "$VEX_WEB_DIR/runconsole.php" 2>/dev/null || true

chmod -R u+rwX,go+rX "$VEX_WEB_DIR" "$VEX_DOCS_DIR"
chmod -R 775 "$VEX_WEB_DIR/vexon/runtime" "$VEX_WEB_DIR/assets" 2>/dev/null || true
chmod 775 "$VEX_LOG_DIR"
chmod 664 "$VEX_LOG_DIR/debug.log" "$VEX_LOG_DIR/rental.log"

if id "$VEX_WEB_USER" >/dev/null 2>&1 && getent group "$VEX_WEB_GROUP" >/dev/null 2>&1; then
  chown -R "$VEX_WEB_USER:$VEX_WEB_GROUP" "$VEX_WEB_DIR" "$VEX_DOCS_DIR" "$VEX_LOG_DIR"
  ok "ownership set to $VEX_WEB_USER:$VEX_WEB_GROUP"
else
  warn "web user/group $VEX_WEB_USER:$VEX_WEB_GROUP not found; skipped chown"
fi

if command -v nginx >/dev/null 2>&1; then
  nginx -t
  if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet nginx; then
    systemctl reload nginx
    ok "nginx reloaded"
  else
    warn "nginx is not active; skipped reload"
  fi
else
  warn "nginx command not found; skipped web server reload"
fi

ok "pool web deployed to $VEX_WEB_DIR"
ok "docs site deployed to $VEX_DOCS_DIR"
