#!/usr/bin/python3

import libtmux
import subprocess
import os
import os.path
from testutils import search_for_pattern, DONE_MARKER, DONE_MARKER_EXPRESSION

SOCKET_NAME='needrestart-tmux'
MOCKUNAME_SO = f'{os.environ.get("AUTOPKGTEST_TMP", "/tmp")}/mockuname.so'

def get_session(server: libtmux.Server, name) -> libtmux.Session:
    return server.new_session(session_name=name, attach=False, window_command='bash -l', x=132, y=80)

def test_kernel_version_mismatch(server: libtmux.Server):
    session = get_session(server, 'needrestart-kernel-mismatch')
    try:
        pane = session.active_pane
        assert pane
        pane.send_keys(f"LANG=C LD_PRELOAD={MOCKUNAME_SO} DEBIAN_FRONTEND=dialog apt reinstall hello && {DONE_MARKER_EXPRESSION}")
        assert search_for_pattern(pane, 'you should consider rebooting')
        assert search_for_pattern(pane, DONE_MARKER)
    finally:
        session.kill()


if __name__ == '__main__':
    subprocess.run(['gcc', '-shared', '-fPIC', '-ldl', 'debian/tests/mockuname.c', '-o', MOCKUNAME_SO], check=True)
    server = libtmux.Server(socket_name=SOCKET_NAME)
    try:
        test_kernel_version_mismatch(server)
    finally:
        server.kill()

