#!/usr/bin/bash
#
# ai-system-info -- Output system information as JSON.
# Used by the BlueOnyx AI agent via sudo to gather system metrics.
#
set -e

PATH=/bin:/usr/bin:/usr/local/bin

# --- Helper: JSON-encode a string ------------------------------------------
json_escape() {
    printf '%s' "$1" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read().rstrip("\n")))'
}

# --- Gather data -----------------------------------------------------------
DISK_JSON=$(python3 -c "
import json, subprocess
try:
    out = subprocess.check_output(['df', '-h', '/', '/var', '/home'], stderr=subprocess.STDOUT, text=True)
except Exception:
    out = ''
print(json.dumps(out))
")

MEMORY=$(free -h 2>/dev/null || echo "free: not available")
MEMORY_JSON=$(json_escape "$MEMORY")

UPTIME=$(uptime -p 2>/dev/null || echo "uptime: not available")
UPTIME_JSON=$(json_escape "$UPTIME")

LOAD=$(cat /proc/loadavg 2>/dev/null || echo "N/A")
LOAD_JSON=$(json_escape "$LOAD")

HOSTNAME=$(hostname 2>/dev/null || echo "unknown")
HOSTNAME_JSON=$(json_escape "$HOSTNAME")

# --- Build JSON output -----------------------------------------------------
cat <<EOF
{
  "hostname": $HOSTNAME_JSON,
  "disk": $DISK_JSON,
  "memory": $MEMORY_JSON,
  "uptime": $UPTIME_JSON,
  "load": $LOAD_JSON
}
EOF

exit 0

# 
# Copyright (c) 2008-2026 Michael Stauber, SOLARSPEED.NET
# Copyright (c) 2008-2026 Team BlueOnyx, BLUEONYX.IT
# All Rights Reserved.
# 
# 1. Redistributions of source code must retain the above copyright 
#    notice, this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright 
#    notice, this list of conditions and the following disclaimer in 
#    the documentation and/or other materials provided with the 
#    distribution.
# 
# 3. Neither the name of the copyright holder nor the names of its 
#    contributors may be used to endorse or promote products derived 
#    from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.
# 
# You acknowledge that this software is not designed or intended for 
# use in the design, construction, operation or maintenance of any 
# nuclear facility.
# 
