#!/usr/bin/env bash
# Run Maven with Chinese DNS / hosts overrides.
# WSL default nameserver (10.255.255.254) often hangs; this bypasses it.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
REAL_HOME="${HOME}"
DNS_DIR="${TMPDIR:-/tmp}/maven-dns-fix"
mkdir -p "$DNS_DIR"
printf 'nameserver 223.5.5.5\nnameserver 119.29.29.29\noptions timeout:2 attempts:2\n' > "$DNS_DIR/resolv.conf"
cat > "$DNS_DIR/hosts" <<'EOF'
127.0.0.1 localhost
::1 localhost
122.228.195.18 maven.aliyun.com
180.163.142.26 repo.huaweicloud.com
61.170.82.70 mirrors.cloud.tencent.com
EOF

if unshare --user --map-root-user --mount true 2>/dev/null; then
  exec unshare --user --map-root-user --mount bash -c "
    mount --bind '$DNS_DIR/resolv.conf' /etc/resolv.conf
    mount --bind '$DNS_DIR/hosts' /etc/hosts
    export HOME='$REAL_HOME'
    export MAVEN_OPTS=\"\${MAVEN_OPTS:-} -Dmaven.repo.local=$REAL_HOME/.m2/repository\"
    cd '$ROOT'
    exec ./mvnw \"\$@\"
  " bash "$@"
else
  echo "warn: unshare unavailable; running ./mvnw without DNS override" >&2
  exec "$ROOT/mvnw" "$@"
fi
