PDF-Report zu smartctl

#!/usr/bin/env bash

DEVICE="$1"

if [[ -z "$DEVICE" ]]; then
    echo "Usage: $0 /dev/sdX"
    exit 1
fi

if ! command -v smartctl >/dev/null; then
    echo "smartctl nicht gefunden."
    exit 1
fi

if ! command -v pandoc >/dev/null; then
    echo "pandoc nicht gefunden."
    exit 1
fi

# --- PDF-Engine wählen ---
if command -v pdflatex >/dev/null; then
    PDF_ENGINE="--pdf-engine=pdflatex"
elif command -v wkhtmltopdf >/dev/null; then
    PDF_ENGINE="--pdf-engine=wkhtmltopdf"
else
    echo "Keine PDF-Engine gefunden (pdflatex oder wkhtmltopdf)."
    echo "Installiere eine davon, z.B.: sudo apt install wkhtmltopdf"
    exit 1
fi

TMPDIR=$(mktemp -d)
JSONFILE="$TMPDIR/smart.json"
REPORTMD="$TMPDIR/report.md"
OUTFILE="smartreport_$(basename "$DEVICE").pdf"

# --- SMART JSON exportieren ---
sudo smartctl -a --json "$DEVICE" > "$JSONFILE"

# --- Grunddaten extrahieren ---
MODEL=$(jq -r '.model_name // "unbekannt"' "$JSONFILE")
SERIAL=$(jq -r '.serial_number // "unbekannt"' "$JSONFILE")
FW=$(jq -r '.firmware_version // "unbekannt"' "$JSONFILE")
CAPACITY=$(jq -r '.user_capacity.bytes // 0' "$JSONFILE")
CAP_GB=$(echo "$CAPACITY / 1024 / 1024 / 1024" | bc)
HEALTH=$(jq -r '.smart_status.passed // false' "$JSONFILE")

# Temperatur: ATA (temperature.current) / NVMe (composite temp)
TEMP=$(jq -r '
    .temperature.current
    // .nvme_smart_health_information_log.temperature
    // "n/a"
' "$JSONFILE")

# --- Report Grundgerüst ---
cat > "$REPORTMD" <<EOF
---
title: "SMART-Report"
subtitle: "$(date +"%Y-%m-%d %H:%M:%S")"
geometry: margin=2cm
---

# Allgemeine Informationen

| Feld            | Wert |
|-----------------|------|
| Gerät           | \`$DEVICE\` |
| Modell          | $MODEL |
| Seriennummer    | $SERIAL |
| Firmware        | $FW |
| Kapazität       | ${CAP_GB} GB |
| Temperatur      | ${TEMP} °C |
| Gesamtstatus    | $( [[ "$HEALTH" == "true" ]] && echo "**OK**" || echo "**NICHT OK**" ) |

---

# SMART-Attribute

Die folgenden Werte wurden automatisch erkannt und eingetragen.

| ID | Name | Aktuell | Schlechtester | Schwellwert | Status |
|----|------|---------|---------------|-------------|--------|
EOF

# --- ATA & NVMe Attribute ---
ATTRIBUTES=$(jq -r '

  # ATA
  if .ata_smart_attributes and .ata_smart_attributes.table then
    .ata_smart_attributes.table[] |
    "| \(.id) | \(.name) | \(.value) | \(.worst) | \(.thresh) | \(.when_failed)"

  # NVMe
  elif .nvme_smart_health_information_log then
    .nvme_smart_health_information_log |
    to_entries[] |
    "| - | \(.key) | \(.value) | - | - | -"

  else
    empty
  end
' "$JSONFILE")

if [[ -z "$ATTRIBUTES" ]]; then
    echo "| (keine SMART-Attribute verfügbar) | | | | | |" >> "$REPORTMD"
else
    echo "$ATTRIBUTES" >> "$REPORTMD"
fi

# --- JSON Rohdaten ---
cat >> "$REPORTMD" <<EOF

---
EOF
# --- PDF erzeugen ---
pandoc "$PDF_ENGINE" "$REPORTMD" -o "$OUTFILE"

echo "PDF erzeugt: $OUTFILE"

rm -rf "$TMPDIR"

Usage:

./smartreport.sh /dev/sda