FROM mzz2017/v2raya:v2.4.9@sha256:47f9acf99b23f19d804ab15303e8a7df7f66913d14c5ce0b39936d036dbb8500

USER root

# v2rayA inside Docker hard-codes "iptables-legacy" and "ip6tables-legacy".
# UmbrelOS ships iptables 1.8.x with nf_tables backend, and v2rayA's redirect
# mode emits REDIRECT rules without a protocol (-p), which both backends reject.
# Replace the legacy binaries with small wrappers that forward to the modern
# iptables and patch the problematic REDIRECT rule on the fly.
RUN set -eux; \
    rm -f /sbin/iptables-legacy /usr/sbin/iptables-legacy \
          /sbin/ip6tables-legacy /usr/sbin/ip6tables-legacy; \
    printf '%s\n' \
        '#!/bin/sh' \
        'has_redirect=0' \
        'has_proto=0' \
        'for arg in "$@"; do' \
        '    case "$arg" in' \
        '        -j) next_is_target=1 ;;' \
        '        REDIRECT) if [ "$next_is_target" = 1 ]; then has_redirect=1; fi; next_is_target=0 ;;' \
        '        -p) has_proto=1 ;;' \
        '    esac' \
        'done' \
        'if [ "$has_redirect" = 1 ] && [ "$has_proto" = 0 ]; then' \
        '    new_args=""' \
        '    inserted=0' \
        '    for arg in "$@"; do' \
        '        if [ "$inserted" = 0 ] && [ "$arg" = "-j" ]; then' \
        '            new_args="$new_args -p tcp"' \
        '            inserted=1' \
        '        fi' \
        '        new_args="$new_args $arg"' \
        '    done' \
        '    set -- $new_args' \
        'fi' \
        'exec iptables "$@"' \
        > /sbin/iptables-legacy; \
    printf '%s\n' \
        '#!/bin/sh' \
        'has_redirect=0' \
        'has_proto=0' \
        'for arg in "$@"; do' \
        '    case "$arg" in' \
        '        -j) next_is_target=1 ;;' \
        '        REDIRECT) if [ "$next_is_target" = 1 ]; then has_redirect=1; fi; next_is_target=0 ;;' \
        '        -p) has_proto=1 ;;' \
        '    esac' \
        'done' \
        'if [ "$has_redirect" = 1 ] && [ "$has_proto" = 0 ]; then' \
        '    new_args=""' \
        '    inserted=0' \
        '    for arg in "$@"; do' \
        '        if [ "$inserted" = 0 ] && [ "$arg" = "-j" ]; then' \
        '            new_args="$new_args -p tcp"' \
        '            inserted=1' \
        '        fi' \
        '        new_args="$new_args $arg"' \
        '    done' \
        '    set -- $new_args' \
        'fi' \
        'exec ip6tables "$@"' \
        > /sbin/ip6tables-legacy; \
    chmod +x /sbin/iptables-legacy /sbin/ip6tables-legacy; \
    ln -s /sbin/iptables-legacy /usr/sbin/iptables-legacy 2>/dev/null || true; \
    ln -s /sbin/ip6tables-legacy /usr/sbin/ip6tables-legacy 2>/dev/null || true

ENTRYPOINT ["v2raya"]
