#! /usr/bin/python3

import syslog, time, glob
from systemd.daemon import notify


def read_int(attr_path):
    try:
        with open(attr_path, "rb") as attr_file:
            return int(attr_file.read())
    except IOError as iox:
        syslog.syslog("TRACKPOINT {} {}".format(attr_path, iox))
        return -1

def write_int(attr_path, val):
    try:
        with open(attr_path, "wb") as attr_file:
            attr_file.write(str(val).encode("ascii"))
    except IOError as iox:
        syslog.syslog("TRACKPOINT {} {}".format(attr_path, iox))

def check_write_int(attr_path, val):
    source = read_int(attr_path)
    if source != val:
        write_int(attr_path, val)
        msg = "TRACKPOINT {} {} {}".format(attr_path, source, val)
        syslog.syslog(msg)


if __name__ == "__main__":
    base_glob = "/sys/devices/platform/i8042/serio1/serio*/"
    sense_glob = base_glob + "sensitivity"
    speed_glob = base_glob + "speed"
    inertia_glob = base_glob + "inertia"
    notify("READY=1")
    syslog.syslog("Trackpoint watchdog started.")
    while True:
        for sense_path in glob.glob(sense_glob):
            check_write_int(sense_path, 200)
        for speed_path in glob.glob(speed_glob):
            check_write_int(speed_path, 130)
        for inertia_path in glob.glob(inertia_glob):
            check_write_int(inertia_path, 4)
        notify("WATCHDOG=1")
        time.sleep(9)
