#!/usr/bin/env python3
import sys
import glob


def read_file(fname):
    try:
        with open(fname) as fp:
            return fp.read().strip()
    except Exception:
        return ''


def collect_klp_patched_module_symbols(mname, pmname):
    ret = []
    paths = glob.glob('/sys/kernel/livepatch/%s/%s/*' % (mname, pmname))
    for p in paths:
        parts = p.split("/")
        symbol_name = parts[-1]
        ret.append(symbol_name.split(',')[0])
    return ret


def get_module_status(module_name):
    base_path = '/sys/kernel/livepatch/%s/' % module_name
    paths = glob.glob(base_path + '*/')
    patch_modules = []
    module_symbols = {}
    for p in paths:
        parts = p.split('/')
        if len(parts) >= 6:
            mname = ''.join(parts[5:])
            patch_modules.append(mname)
            module_symbols[mname] = collect_klp_patched_module_symbols(module_name, mname)

    ret = {
        'name': module_name,
        'enabled': read_file(base_path + 'enabled'),
        'transition': read_file(base_path + 'transition'),
        'patch_modules': patch_modules,
        'patch_symbols': module_symbols,
        'force_path': base_path + 'force',
        'enabled_path': base_path + 'enabled',
    }
    return ret


def get_status(t):
    if t == '1':
        return 'PENDING'
    else:
        return 'PATCHED'


def output_module_status(modules):
    print('Module    \tEnabled\tStatus\tPatch Modules')
    for status in modules:
        print("%10s\t%s\t%s\t%s" % (status['name'], status['enabled'], get_status(status['transition']), ', '.join(status['patch_modules'])))


def list_klp_modules():
    modules = []
    paths = glob.glob('/sys/kernel/livepatch/*')
    for path in paths:
        parts = path.split('/')
        if len(parts) != 5:
            continue
        module_name = parts[4]
        status = get_module_status(module_name)
        modules.append(status)
    return modules


def output_list_klp_modules():
    modules = list_klp_modules()
    output_module_status(modules)


def do_force_klp_module(m):
    fpath = m['force_path']
    try:
        with open(fpath, 'w') as fp:
            fp.write("1")
    except Exception as e:
        print("Error: %s" % e)


def do_disable_klp_module(m):
    fpath = m['enabled_path']
    try:
        with open(fpath, 'w') as fp:
            fp.write('0')
    except Exception as e:
        print("Error: %s" % e)


def force_klp_module(args):
    if len(args) < 2:
        print('please input klp module name')
        return

    modules = list_klp_modules()
    for m in modules:
        if m['name'] == args[1]:
            if m['enabled'] == '1':
                if m['transition'] == '1':
                    do_force_klp_module(m)
                    return
                else:
                    print('module already patched')
                    return
            elif m['enabled'] == '0':
                if m['transition'] == '1':
                    do_force_klp_module(m)
                    return
                else:
                    print('module already disabled')
                    return
    print('cannot find livepatch module %s' % args[1])


def disable_klp_module(args):
    if len(args) < 2:
        print('please input klp module name')
        return

    modules = list_klp_modules()
    for m in modules:
        if m['name'] == args[1]:
            if m['enabled'] == '1':
                if m['transition'] == '1':
                    print("klp module in transition mode")
                    return
                else:
                    do_disable_klp_module(m)
                    return
            else:
                print('module already disabled')
                return
    print('cannot find livepatch module %s' % args[1])


def output_klp_module_info(args):
    if len(args) < 2:
        print('please input klp module name')
        return

    modules = list_klp_modules()
    for m in modules:
        if m['name'] == args[1]:
            print_klp_module_info(m)
            return
    print('cannot find livepatch module %s' % args[1])


def print_klp_module_info(m):
    print("Module Name: %s" % m['name'])
    print("Enabled:     %s" % m['enabled'])
    print("Status:      %s" % get_status(m['transition']))
    print("Patch Modules:")
    for mn in m['patch_modules']:
        print('  Module: %s' % mn)
        for symbol in m['patch_symbols'].get(mn, []):
            print('    Symbol: %s' % symbol)


def print_process_info(pid):
    comm = read_file('/proc/%s/comm' % pid)
    stat = read_file('/proc/%s/stat' % pid)
    parts = stat.split()
    if len(parts) < 9:
        return
    m = int(parts[8])
    if m & 0x00200000 > 0:
        print("KTHREAD %s %s" % (pid, comm))
    else:
        print("PROCESS %s %s" % (pid, comm))


def check_klp_stuck_processes():
    paths = glob.glob("/proc/*/patch_state")
    has_stucks = False
    for p in paths:
        parts = p.split('/')
        if len(parts) < 3:
            continue
        pid = parts[2]
        try:
            with open(p) as fp:
                pstat = fp.read().strip()
                if pstat == '0':
                    has_stucks = True
                    print_process_info(pid)
        except Exception:
            pass

    if not has_stucks:
        print('No stuck process')


def print_help():
    print("klptools [command]")
    print("Commands:")
    print("  list:        list kernel livepatch modules and show the status")
    print("  info:        show kernel livepatch module info")
    print("  force:       force kernel livepatch module")
    print("  disable:     disable kernel livepatch module")
    print("  check-stuck: check process livepatch status")
    print("  help:        show this help")


def main(args):
    if len(args) < 2:
        print_help()
        return

    cmd = args[1]
    if cmd == 'list':
        output_list_klp_modules()
    elif cmd == 'info':
        output_klp_module_info(args[1:])
    elif cmd == 'force':
        force_klp_module(args[1:])
    elif cmd == 'check-stuck':
        check_klp_stuck_processes()
    elif cmd == 'help':
        print_help()
    elif cmd == 'disable':
        disable_klp_module(args[1:])
    else:
        print_help()


if __name__ == '__main__':
    args = sys.argv
    main(args)
