#!/bin/sh
set -e

export AUTOPKGTEST_TMP=${AUTOPKGTEST_TMP:-/tmp/adt-smartctl-exporter-smoke}
mkdir -p "$AUTOPKGTEST_TMP"

failed=0

check() {
    if [ $1 -eq 0 ]; then
        echo "  PASS: $2"
    else
        echo "  FAIL: $2 (exit $1)"
        failed=$((failed + 1))
    fi
}

echo "smartctl-exporter autopkgtest — smoke test"
echo "========================================="

# 1. Binary exists
BIN="/usr/bin/smartctl_exporter"
[ -x "$BIN" ] || BIN="/usr/sbin/smartctl_exporter"
if [ -x "$BIN" ]; then
    echo "  PASS: binary found at $BIN"
else
    echo "  FAIL: smartctl_exporter binary not found"
    failed=$((failed + 1))
fi

# 2. --help and --version
"$BIN" --help >/dev/null 2>&1; check $? "--help"
"$BIN" --version >/dev/null 2>&1; check $? "--version"

# 3. Key flag parsing (no dry-run flag exists)
"$BIN" --web.listen-address=:0 --smartctl.device-include='^/dev/loop' >/dev/null 2>&1 &
PID=$!
sleep 1
kill $PID 2>/dev/null || true
wait $PID 2>/dev/null || true
# kill returns 143 (SIGTERM) which is expected
if [ $? -eq 0 ] || [ $? -eq 143 ]; then
    echo "  PASS: flag parsing (--web.listen-address, --smartctl.device-include)"
else
    echo "  FAIL: flag parsing (--web.listen-address, --smartctl.device-include)"
    failed=$((failed + 1))
fi

# 4. Systemd unit (check both common paths)
SYSTEMD_UNIT=""
for path in /lib/systemd/system/prometheus-smartctl-exporter.service /usr/lib/systemd/system/prometheus-smartctl-exporter.service; do
    if [ -f "$path" ]; then
        SYSTEMD_UNIT="$path"
        break
    fi
done
if [ -n "$SYSTEMD_UNIT" ]; then
    systemd-analyze verify "$SYSTEMD_UNIT" >/dev/null 2>&1
    check $? "systemd unit verification ($SYSTEMD_UNIT)"
else
    echo "  SKIP: systemd unit not found"
fi

# 5. Device scan on loop device (if available)
if ls /dev/loop* >/dev/null 2>&1; then
    LOOP_DEV=$(ls /dev/loop* | head -1)
    "$BIN" --smartctl.device="$LOOP_DEV" --web.listen-address=:0 --smartctl.interval=1s >/dev/null 2>&1 &
    PID=$!
    sleep 2
    kill $PID 2>/dev/null || true
    wait $PID 2>/dev/null || true
    # kill returns 143 (SIGTERM) which is expected
    if [ $? -eq 0 ] || [ $? -eq 143 ]; then
        echo "  PASS: device scan on $LOOP_DEV"
    else
        echo "  FAIL: device scan on $LOOP_DEV"
        failed=$((failed + 1))
    fi
else
    echo "  SKIP: no loop devices for device scan test"
fi

echo "========================================="
if [ $failed -gt 0 ]; then
    echo "FAILED: $failed test(s)"
    exit 1
else
    echo "ALL SMOKE TESTS PASSED"
fi