#!/bin/bash
set -euo pipefail
umask 077

usage() {
    printf '%s\n' 'Usage: lhm-hardware-diagnostic-archive [--memory-timings | --pm-table | --connect-pm-table | --board-sensors] [--directory ABSOLUTE_PATH] [--authorize]' \
        'Run as your desktop user. Use --authorize to request protected reads through the installed Polkit action.'
}
option=
directory=
authorize=false
while (( $# )); do
    case "$1" in
        --help) usage; exit 0 ;;
        --memory-timings|--pm-table|--connect-pm-table|--board-sensors)
            [[ -z "$option" ]] || { usage >&2; exit 2; }
            option=$1 ;;
        --directory)
            [[ $# -ge 2 && "$2" = /* ]] || { usage >&2; exit 2; }
            directory=$2
            shift ;;
        --authorize) authorize=true ;;
        *) usage >&2; exit 2 ;;
    esac
    shift
done
if (( EUID == 0 )); then
    usage >&2
    exit 2
fi
if [[ -z "$directory" ]]; then
    documents=$(xdg-user-dir DOCUMENTS 2>/dev/null || :)
    if [[ "$documents" != /* ]]; then
        documents="$HOME/Documents"
    fi
    directory="$documents/Linux Hardware Monitor"
fi
if ! mkdir -p -- "$directory" || ! run=$(mktemp -d -- "$directory/lhm-diagnostic-$(date -u +%Y%m%d-%H%M%S).XXXXXX"); then
    printf 'Cannot write to %s. Select another directory with --directory.\n' "$directory" >&2
    exit 1
fi

tools=$(dirname "$(realpath -- "$0")")
collector="$tools/lhm-hardware-diagnostics"
installed=/usr/libexec/linux-hw-monitor/lhm-hardware-diagnostics
args=()
[[ -z "$option" ]] || args+=("$option")
user_args=("${args[@]}")
if [[ "$option" = --board-sensors ]]; then
    user_args+=(--board-output "$tools/../../bin/linux-hw-monitor" "$run")
fi

finish() {
    local code=$?
    trap - EXIT
    trap '' INT TERM
    local archive="$run.tar.gz"
    printf '%s\n' "$code" > "$run/session-exit.txt"
    if tar -czf "$archive.part" -C "$run" . && mv -T -- "$archive.part" "$archive"; then
        printf '\n%s\n' "$archive"
    else
        printf 'Cannot save an archive in %s. Select another directory with --directory. Results: %s\n' "$directory" "$run" >&2
        exit 1
    fi
    exit "$code"
}
trap finish EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
"$collector" --user "${user_args[@]}" > "$run/user.jsonl" 2> "$run/user.stderr"
mapfile -t retry < <(/usr/bin/python3 -IB - "$run/user.jsonl" <<'PY'
import json
import sys

with open(sys.argv[1], encoding="utf-8") as rows:
    for line in rows:
        row = json.loads(line)
        if row.get("probe") == "authorization" and row.get("status") == "required":
            print("--privileged")
            if row.get("aperf_retry"):
                print("--retry-perf")
            if row.get("publication_retry"):
                print("--retry-publications")
            break
PY
)
if (( ${#retry[@]} )); then
    if "$authorize"; then
        /usr/bin/pkexec "$installed" "${retry[@]}" "${args[@]}" > "$run/protected.jsonl" 2> "$run/protected.stderr"
    else
        printf '%s\n' 'Protected stages skipped. Run with --authorize to request administrator access.' > "$run/protected.stderr"
    fi
fi
