
from __future__ import absolute_import
from __future__ import division
import logging

from vdsm.common import cmdutils
from vdsm.common import commands

_UDEVADM = cmdutils.CommandPath(
    "udevadm", "/sbin/udevadm", "/usr/sbin/udevadm")


def settle(timeout, exit_if_exists=None):
    args = ["settle", "--timeout=%s" % timeout]

    if exit_if_exists:
        args.append("--exit-if-exists=%s" % exit_if_exists)

    try:
        _run_command(args)
    except cmdutils.Error as e:
        logging.error("%s", e)


def trigger(attr_matches=(), property_matches=(), subsystem_matches=()):
    _run_command(['control', '--reload'])

    cmd = ['trigger', '--verbose', '--action', 'change']

    for name, value in property_matches:
        cmd.append('--property-match={}={}'.format(name, value))

    for name, value in attr_matches:
        cmd.append('--attr-match={}={}'.format(name, value))

    for name in subsystem_matches:
        cmd.append('--subsystem-match={}'.format(name))

    _run_command(cmd)


def _run_command(args):
    cmd = [_UDEVADM.cmd]
    cmd.extend(args)
    rc, out, err = commands.execCmd(cmd, raw=True)
    if rc != 0:
        raise cmdutils.Error(cmd, rc, out, err)
