#!/usr/bin/env python3
import os
import subprocess
import json
import time
import threading

# erase unused fifos
for pid in os.listdir("/run/etap/{}".format(os.getuid())):
    if not pid.isnumeric():
        continue
    if not os.path.isdir("/proc/{}".format(pid)):
        os.unlink("/run/etap/{}/{}".format(os.getuid(), pid))

# create fifo
fifo = "/run/etap/{}/{}".format(os.getuid(), os.getpid())

# wait until trigger
while True:
    data = []
    if os.path.exists(fifo):
        os.remove(fifo)
    os.mkfifo(fifo)
    os.chmod(fifo, 0o700)
    try:
        with open(fifo,"r") as f:
            data = json.loads(f.read())
    except:
        time.sleep(5)
        pass

    if "action" in data:
        if data["action"] == "quit":
            # exit session
            subprocess.run(["cinnamon-session-quit", "--no-prompt", "--force"])
        elif data["action"] == "lock":
            subprocess.run(["cinnamon-screensaver-command", "--lock"])
        elif data["action"] == "run" and "command" in data:
            th = threading.Thread(target=subprocess.run, args=(data["command"]))
            th.start()
