#!/bin/bash
[ "$2" == "" ] && exec echo "Usage: $0 <SET_ID> <CONFIG_NAME>"

SET_ID=$1
CONFIG_NAME=$2

env LANG=C /usr/bin/mrtg ${CONFIG_NAME} || true

# Atomic write index.html — 防 indexmaker 失敗時 `>` redirect 把 index.html 砍成 0 bytes
INDEX_TMP="index.html.tmp.$$"
INDEX_ERR=$(mktemp)
if /usr/bin/indexmaker --title="MRTG Index Page SET${SET_ID}" ${CONFIG_NAME} > "$INDEX_TMP" 2> "$INDEX_ERR"; then
    mv "$INDEX_TMP" index.html
    if [ -s "$INDEX_ERR" ]; then
        echo "WARN: indexmaker 有訊息:" >&2
        cat "$INDEX_ERR" >&2
    fi
    rm -f "$INDEX_ERR"
else
    rc=$?
    echo "ERROR: indexmaker 失敗 (rc=$rc):" >&2
    cat "$INDEX_ERR" >&2
    rm -f "$INDEX_TMP" "$INDEX_ERR"
    exit 1
fi
