#! /usr/bin/python3
import os
import subprocess
import sys
sys.path.append("//lib/mstpctl-utils/")

from ifquery_helper import ifquery
DAEMON = "/sbin/mstpd"
mstpd_conf_file = "/etc/default/mstpd"
opt_args = ""
pvrst_cmdline = "mstpctl-pvrst-mode yes"
pvrst_cmdline = pvrst_cmdline.encode("utf-8")
enable_pvrst = ""

try:
    # Read the optional args from the /etc/default/mstpd
    if os.path.exists(mstpd_conf_file):
        with open(mstpd_conf_file, "r") as mstpd_conf:
            conf_str = mstpd_conf.read().splitlines()
            for line in conf_str:
                if "DAEMON_OPT_ARGS" in line:
                    (name, opt_args) = line.split("=")
                    break;

    ifinfo = ifquery()
    if ifinfo and (ifinfo.find(pvrst_cmdline) != -1):
        enable_pvrst = "-m pvrst"

except Exception as e:
    print(("Failed to parse the interface config file %s", str(e)))
    pass

os.system("exec {0}  -d {1} {2}" .format(DAEMON, opt_args, enable_pvrst))
