# Copyright 2022 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.
"""Common utility methods."""

import logging
import subprocess

logger = logging.getLogger(__name__)


class Configuration:
    """Configuration setup for the integration tests."""

    BASE_URL = 'http://localhost'
    DEBUSINE_SERVER_USER = 'debusine-server'


def run_as(user, cmd, *, stdin=None):
    """Run cmd as user using sudo."""
    cmd = ['sudo', '-u', user] + cmd

    return run(cmd, stdin=stdin)


def run(cmd, *, stdin=None):
    """Run cmd with stdin, return subprocess.CompletedProcess."""
    kwargs = {}
    if stdin is not None:
        kwargs['input'] = stdin

    logger.debug('Exec: %s (stdin: %s)', cmd, stdin)

    result = subprocess.run(
        cmd,
        universal_newlines=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        **kwargs,
    )

    return result


def run_background(cmd):
    """Run cmd, assert returncode==0, return subprocess.Popen."""
    logger.debug('Exec (background): %s', cmd)

    result = subprocess.Popen(cmd)

    assert result.returncode == 0
    return result
