#!/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2025 Harald Sitter <sitter@kde.org>

import subprocess
import time
from pathlib import Path
import json

callback = None
with open('/proc/cmdline') as cmdline:
    data = cmdline.read()
    entries = data.split(' ')
    for entry in entries:
        if entry.startswith('kde-linux.basic-test-callback='):
            # We don't support quoting of any kind.
            callback = entry.split('=', 2)[1]
            callback = callback.strip()
            break

if callback is None:
    print('No callback specified. set kde-linux.basic-test-callback=')
    exit(1)

bad_callback = callback.replace('/good', '/bad')

while True:
    # 1000 is the uid of the live user. always.
    if Path('/run/user/1000/kde-linux-bless-session').is_file():
        failed = json.loads(subprocess.check_output(["systemctl", "--failed", "--output=json"]))
        if len(failed) > 0:
            with open('data.file', 'w') as f:
                for unit in failed:
                    f.write("\n")
                    f.write(json.dumps(unit))
                    f.write("\n")
                    try:
                        f.write(subprocess.check_output(['journalctl', '--no-pager', f'_SYSTEMD_UNIT={unit['unit']}']).decode('utf-8'))
                    except Exception as e:
                        f.write(f"Failed to get journal for {unit['unit']}: {e}\n")
                f.write("\n") # make sure we have a final newline
            subprocess.check_call(['curl',
                                   '--request', 'GET',
                                   '--data-binary', '@data.file', # use binary as otherwise curl will eat the newlines
                                   bad_callback])
        else:
            subprocess.check_call(['curl', callback])
    time.sleep(30)
