#!/opt/alt/python38/bin/python3.8
"""
The script wraps dumping/loading functionality for wsshdict
to set timeouts for it to prevent stacking the hanged processes.
Current dump/load cycle is the workaround to get rid of old entries (they are
skipped on loading)
"""


import os
import subprocess

BINARY = "/opt/imunify360-webshield/bin/sc"
SOCK_PATH = "/var/run/wsshdict/wsshdict.sock"
DUMP_PATH = "/opt/imunify360-webshield/shared_data/.wsdump.yml"


def run_command(dump=True, timeout=3):
    cmd = '-D' if dump else '-L'
    args = [BINARY, '-s', SOCK_PATH, cmd, '-v', DUMP_PATH]
    try:
        subprocess.run(
            args,
            stdin=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=True,
            timeout=timeout)
    except Exception:
        return False
    return True


def mkdump(timeout=16):
    return run_command(dump=True, timeout=timeout)


def mkload(timeout=24):
    return run_command(dump=False, timeout=timeout)


def mkclean():
    try:
        os.unlink(DUMP_PATH)
    except FileNotFoundError:
        return True
    except Exception:
        return False
    return True


def main():
    if not mkclean():
        return
    for f in mkdump, mkload:
        if not f():
            break
    mkclean()
    

if __name__ == '__main__':
    main()
