#!/bin/bash
# Status Panel Agent
# 用法: ./agent.sh <服务器地址> <密钥>

SERVER="${1:-http://your-server:3800}"
SECRET="$2"

[ -z "$SECRET" ] && echo "Usage: $0 <server> <secret>" && exit 1

# 获取CPU使用率
get_cpu() {
  local idle=$(top -bn1 | grep "Cpu(s)" | awk '{print $8}' | cut -d'%' -f1)
  [ -z "$idle" ] && idle=$(top -bn1 | grep "%id" | awk '{print $8}')
  echo "scale=1; 100 - $idle" | bc 2>/dev/null || echo "0"
}

# 获取内存
get_mem() {
  local mem=$(free -b | grep Mem)
  echo "$(echo $mem | awk '{print $3}'),$(echo $mem | awk '{print $2}')"
}

# 获取磁盘
get_disk() {
  local disk=$(df -B1 / | tail -1)
  echo "$(echo $disk | awk '{print $3}'),$(echo $disk | awk '{print $2}')"
}

# 获取网络流量
get_net() {
  local net=$(cat /proc/net/dev | grep -E 'eth0|ens|enp' | head -1)
  echo "$(echo $net | awk '{print $2}'),$(echo $net | awk '{print $10}')"
}

# 获取负载
get_load() {
  cat /proc/loadavg | awk '{print $1","$2","$3}'
}

# 获取运行时间
get_uptime() {
  cat /proc/uptime | awk '{print int($1)}"
}

while true; do
  cpu=$(get_cpu)
  mem=(${(get_mem)//,/ })
  disk=(${(get_disk)//,/ })
  net=(${(get_net)//,/ })
  load=(${(get_load)//,/ })
  uptime=$(get_uptime)
  
  curl -s -X POST "$SERVER/report" \
    -H "Content-Type: application/json" \
    -d "{
      \"secret\": \"$SECRET\",
      \"cpu\": $cpu,
      \"mem_used\": ${mem[0]},
      \"mem_total\": ${mem[1]},
      \"disk_used\": ${disk[0]},
      \"disk_total\": ${disk[1]},
      \"net_in\": ${net[0]},
      \"net_out\": ${net[1]},
      \"uptime\": $uptime,
      \"load1\": ${load[0]},
      \"load5\": ${load[1]},
      \"load15\": ${load[2]}
    }" > /dev/null 2>&1
  
  sleep 30
done
