#!/bin/sh
# Synology DSM - tarea programada compacta. Usuario recomendado: root.

URL="https://10.100.21.46/intranet/apps/inventario/api.php"
TOKEN="oOivy8mNU1md35MFYGRrTy+AUQKlVk1dR85bGXDoDZo="
TIMEOUT="60"
IGNORE_TLS="1"

esc(){ printf '%s' "$1" | sed 's/\\/\\\\/g;s/"/\\"/g;s/	/ /g'; }
j(){ printf '"%s"' "$(esc "$1")"; }
n(){ [ -n "$1" ] && printf '%s' "$1" || printf 'null'; }
r(){ [ -r "$1" ] && sed -n '1p' "$1" 2>/dev/null || true; }

[ -n "$TOKEN" ] && [ "$TOKEN" != "PEGA_AQUI_EL_TOKEN" ] || { echo "Configura TOKEN." >&2; exit 1; }
command -v curl >/dev/null 2>&1 || { echo "curl no esta disponible en DSM." >&2; exit 1; }

HOST="$(hostname 2>/dev/null || r /etc/hostname)"
FQDN="$(hostname -f 2>/dev/null || echo "$HOST")"
DOMAIN=""
case "$FQDN" in *.*) DOMAIN="${FQDN#*.}";; esac

MODEL="$(r /proc/sys/kernel/syno_hw_version)"
[ -n "$MODEL" ] || MODEL="$(r /proc/sys/kernel/syno_hw_revision)"
SERIAL="$(r /proc/sys/kernel/syno_serial)"
VERFILE="/etc.defaults/VERSION"
[ -r "$VERFILE" ] || VERFILE="/etc/VERSION"
PRODUCT="$(grep '^productversion=' "$VERFILE" 2>/dev/null | cut -d= -f2 | tr -d '"')"
BUILD="$(grep '^buildnumber=' "$VERFILE" 2>/dev/null | cut -d= -f2 | tr -d '"')"
SMALL="$(grep '^smallfixnumber=' "$VERFILE" 2>/dev/null | cut -d= -f2 | tr -d '"')"
CAPTION="Synology DSM"
[ -n "$PRODUCT" ] && [ -n "$BUILD" ] && CAPTION="DSM $PRODUCT-$BUILD"
[ -n "$SMALL" ] && [ "$SMALL" != "0" ] && CAPTION="$CAPTION-$SMALL"

RAM="$(awk '/MemTotal:/ {printf "%.2f",$2/1048576}' /proc/meminfo 2>/dev/null)"
CPU="$(awk -F: '/model name|Hardware/ {gsub(/^[ \t]+/,"",$2); print $2; exit}' /proc/cpuinfo 2>/dev/null)"
ARCH="$(uname -m 2>/dev/null)"
KERNEL="$(uname -r 2>/dev/null)"
NOW="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
USER_NOW="$(id -un 2>/dev/null || whoami 2>/dev/null || echo root)"

DISK_LINE="$(df -Pk /volume[0-9]* / 2>/dev/null | awk 'NR>1 && $2>0 {p=$4/$2; if(n==0 || p<best){n=1; best=p; m=$6; t=$2/1048576; f=$4/1048576}} END{if(n) printf "%s|%.2f|%.2f",m,t,f}')"
OLDIFS="$IFS"; IFS='|'; set -- $DISK_LINE; IFS="$OLDIFS"
MOUNT="$1"; DTOTAL="$2"; DFREE="$3"
[ -n "$MOUNT" ] || MOUNT="/"

NET=""
for P in /sys/class/net/*; do
  IFACE="${P##*/}"
  [ "$IFACE" = "lo" ] && continue
  MAC="$(r "$P/address")"
  [ -n "$MAC" ] && [ "$MAC" != "00:00:00:00:00:00" ] || continue
  STATE="$(r "$P/operstate")"
  IP=""
  if command -v ip >/dev/null 2>&1; then
    IP="$(ip -o -4 addr show dev "$IFACE" 2>/dev/null | awk 'NR==1{split($4,a,"/");print a[1]}')"
  fi
  [ -n "$IP" ] || IP="$(ifconfig "$IFACE" 2>/dev/null | awk '/inet /{print $2; exit}' | sed 's/addr://')"
  WOL="Desconocido"
  if command -v ethtool >/dev/null 2>&1; then
    W="$(ethtool "$IFACE" 2>/dev/null | awk -F: '/Wake-on/{gsub(/ /,"",$2); print $2; exit}')"
    case "$W" in *g*) WOL="Enabled";; d) WOL="Disabled";; esac
  fi
  IPV4="[]"; [ -n "$IP" ] && IPV4="[$(j "$IP")]"
  ITEM="{\"name\":$(j "$IFACE"),\"interface_description\":$(j "$IFACE"),\"status\":$(j "$STATE"),\"mac_address\":$(j "$MAC"),\"link_speed\":\"\",\"ipv4\":$IPV4,\"ipv6\":[],\"wake_on_magic_packet\":$(j "$WOL")}"
  NET="${NET:+$NET,}$ITEM"
done

JSON="{\"inventory_version\":\"linux-1.0\",\"collected_at\":$(j "$NOW"),\"computer\":{\"name\":$(j "$HOST"),\"domain\":$(j "$DOMAIN"),\"manufacturer\":\"Synology\",\"model\":$(j "$MODEL"),\"serial_number\":$(j "$SERIAL"),\"bios_version\":null},\"os\":{\"caption\":$(j "$CAPTION"),\"version\":$(j "$PRODUCT"),\"build\":$(j "$KERNEL"),\"architecture\":$(j "$ARCH"),\"install_date\":null,\"last_boot_up_time\":null},\"hardware\":{\"processor\":$(j "$CPU"),\"ram_gb\":$(n "$RAM"),\"disks\":[{\"device_id\":$(j "$MOUNT"),\"volume_name\":$(j "$MOUNT"),\"total_gb\":$(n "$DTOTAL"),\"free_gb\":$(n "$DFREE")}]},\"users\":{\"current_user\":$(j "$USER_NOW"),\"last_logged_on\":$(j "$USER_NOW"),\"previous_domain_users\":[]},\"network\":[$NET],\"software\":[]}"

CURL_OPTS="-sS --max-time $TIMEOUT"
[ "$IGNORE_TLS" = "1" ] && CURL_OPTS="$CURL_OPTS -k"
TMP="${TMPDIR:-/tmp}/invapi.$$"
CODE="$(curl $CURL_OPTS -o "$TMP" -w "%{http_code}" -X POST "$URL" -H "Content-Type: application/json; charset=utf-8" -H "X-Inventory-Token: $TOKEN" -H "X-Inventory-Agent: intranet-inventory-synology-compact/1.0" --data-binary "$JSON")" || { rm -f "$TMP"; exit 1; }
RESP="$(cat "$TMP" 2>/dev/null)"; rm -f "$TMP"
[ "$CODE" = "200" ] || { echo "HTTP $CODE: $RESP" >&2; exit 1; }
echo "$RESP" | grep -q '"ok"[[:space:]]*:[[:space:]]*true' && echo "Inventario enviado: $HOST" || { echo "$RESP" >&2; exit 1; }
