#!/bin/sh
# system_logs_dmesg — read kernel ring buffer or log files
set -e
input=$(cat)
lines=$(echo "$input" | jq -r '.lines // "30"')
source=$(echo "$input" | jq -r '.source // "dmesg"')
grep_pat=$(echo "$input" | jq -r '.grep // empty')

if [ "$source" = "dmesg" ]; then
    if [ -n "$grep_pat" ]; then
        dmesg --time-format iso | tail -n "$lines" | grep -i "$grep_pat"
    else
        dmesg --time-format iso | tail -n "$lines"
    fi
else
    # Absolute path to a log file
    if [ ! -f "$source" ]; then
        echo "error: log file not found: $source" >&2
        exit 1
    fi
    if [ -n "$grep_pat" ]; then
        tail -n "$lines" "$source" | grep -i "$grep_pat"
    else
        tail -n "$lines" "$source"
    fi
fi
