#!/bin/sh /etc/rc.common
# Router VPN Auto-Start for newifi D2
# 每次上电从服务器下载二进制，PassWall 配置保留在路由器本地

START=99

# ====== 改这里！你的服务器地址 ======
SERVER="http://YOUR_SERVER_IP:PORT/router_vpn"
# =====================================

log()  { echo "[vpn] $*"; }

start() {
    log "Waiting for network..."
    while ! ping -c1 -W2 223.5.5.5 >/dev/null 2>&1; do sleep 1; done
    log "Network ready."

    # 下载 sing-box（每1秒重试直到成功）
    log "Downloading sing-box..."
    while ! wget -q -O /tmp/sing-box-v2.gz "$SERVER/sing-box-v2.gz"; do sleep 1; done
    gunzip -f /tmp/sing-box-v2.gz
    chmod +x /tmp/sing-box-v2
    ln -sf /tmp/sing-box-v2 /usr/bin/sing-box
    log "sing-box OK."

    # 下载 xray
    log "Downloading xray..."
    while ! wget -q -O /tmp/xray.gz "$SERVER/xray.gz"; do sleep 1; done
    gunzip -f /tmp/xray.gz
    chmod +x /tmp/xray
    ln -sf /tmp/xray /usr/bin/xray
    log "xray OK."

    log "Starting PassWall..."
    /etc/init.d/passwall start
    log "Done."
}

stop() {
    /etc/init.d/passwall stop 2>/dev/null
    killall sing-box 2>/dev/null
    killall xray 2>/dev/null
    rm -f /tmp/sing-box-v2 /tmp/sing-box-v2.gz /tmp/xray /tmp/xray.gz
}
