#!/bin/bash
# Status Panel Agent

SECRET="$1"
SERVER="$2"

if [ -z "$SECRET" ] || [ -z "$SERVER" ]; then
  echo "Usage: $0 <secret> <server_url>"
  echo "Example: $0 abc123 http://1.2.3.4:3800"
  exit 1
fi

while true; do
  # CPU
  CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1 2>/dev/null || echo 0)
  [ -z "$CPU" ] && CPU=$(top -bn1 | awk '/%Cpu/ {print $2}' | head -1)
  
  # Memory
  MEM_INFO=$(free -b | awk '/Mem:/ {print $3,$2}')
  MEM_USED=$(echo $MEM_INFO | awk '{print $1}')
  MEM_TOTAL=$(echo $MEM_INFO | awk '{print $2}')
  
  # Disk
  DISK_INFO=$(df -B1 / | awk 'NR==2 {print $3,$2}')
  DISK_USED=$(echo $DISK_INFO | awk '{print $1}')
  DISK_TOTAL=$(echo $DISK_INFO | awk '{print $2}')
  
  # Network (需要计算差值)
  NET_INFO=$(cat /proc/net/dev | grep -E 'eth0|ens|enp' | awk '{print $2,$10}')
  NET_IN=$(echo $NET_INFO | awk '{print $1}')
  NET_OUT=$(echo $NET_INFO | awk '{print $2}')
  
  # Uptime
  UPTIME=$(cat /proc/uptime | awk '{print int($1)}')
  
  # Load
  LOAD=$(cat /proc/loadavg | awk '{print $1,$2,$3}')
  LOAD1=$(echo $LOAD | awk '{print $1}')
  LOAD5=$(echo $LOAD | awk '{print $2}')
  LOAD15=$(echo $LOAD | awk '{print $3}')
  
  # Send
  curl -s -X POST "$SERVER/report" \
    -H "Content-Type: application/json" \
    -d "{
      \"secret\": \"$SECRET\",
      \"cpu\": $CPU,
      \"mem_used\": $MEM_USED,
      \"mem_total\": $MEM_TOTAL,
      \"disk_used\": $DISK_USED,
      \"disk_total\": $DISK_TOTAL,
      \"net_in\": $NET_IN,
      \"net_out\": $NET_OUT,
      \"uptime\": $UPTIME,
      \"load1\": $LOAD1,
      \"load5\": $LOAD5,
      \"load15\": $LOAD15
    }" > /dev/null 2>&1
  
  sleep 5
done
