#!/usr/bin/env python3
import os
import sys
import time
import pickle

sys.path.insert(0,"/usr/share/etausb/")

if os.path.exists("/etc/etausb.debug"):
    sys.stdout = open("/var/log/etausb.udev.log","a")
    sys.stderr = open("/var/log/etausb.udev.log","a")


udata = os.environ.copy()
for name in ["ACTION", "DEVTYPE", "SUBSYSTEM"]:
    if name not in udata:
        exit(0)
if udata["ACTION"] not in ["add", "remove"]:
    exit(0)
if udata["SUBSYSTEM"] != "block":
    exit(0)
if udata["DEVTYPE"] != "partition":
    exit(0)

if os.path.exists("/etc/etausb.debug"):
    with open("/var/log/etausb.env","w") as f:
        print(udata, file=f)


os.makedirs("/run/etap/", exist_ok=True)

# ignore if service down
if not os.path.exists("/run/etap/trigger"):
    exit(0)

# Bad way to lock / unlock fifo
while os.path.isfile("/run/etap/trigger.lock"):
    time.sleep(0.1)

open("/run/etap/trigger.lock","w").close()

print(udata["DEVNAME"])
with open("/run/etap/trigger","wb") as f:
    pickle.dump(udata, f)

if os.path.isfile("/run/etap/trigger.lock"):
    os.remove("/run/etap/trigger.lock")
