# Path: lib/exception.py
# class BaseException(Exception):
# class RequiredParameterMissing(BaseException):
# class DistributionError(BaseException):
# class DistributionDetectionError(DistributionError):
# class DistributionNotSupportedError(DistributionError):
# class DistributionVersionNotSupportedError(DistributionError):
# class PackageError(BaseException):
# class PackageSpecError(PackageError):
# class PackageDescriptorError(PackageError):
# class PackageDirectoryIsEmpty(PackageError):
# class RepositoryError(BaseException):
# class SubprocessError(BaseException):
# class TimeoutError(BaseException):
# class FilesToValidateNotFound(BaseException):
# class NoPackagesUpdated(BaseException):
#     DEFAULT_MESSAGE = "Failed to build packages"
#     DEFAULT_MESSAGE = "Required parameter '%(parameter)s' is missing"
#     DEFAULT_MESSAGE = "Distribution not Supported"
#     DEFAULT_MESSAGE = "Failed to detect system's GNU/Linux distribution"
#     DEFAULT_MESSAGE = "%(distribution)s distribution is not supported"
#     DEFAULT_MESSAGE = "%(distribution)s version %(version)s is not supported"
#     DEFAULT_MESSAGE = "Failed to gather %(package)s's information"
#     DEFAULT_MESSAGE = (
#         "%(package)s's spec for %(distro)s %(distro_version)s not Found.")
#     DEFAULT_MESSAGE = "Missing data in %(package)s's YAML descriptor"
#     DEFAULT_MESSAGE = "No packages to build. Packages directory is empty."
#     DEFAULT_MESSAGE = (
#         "Failed to setup %(repo_name)s's repository at %(repo_path)s.")
#     DEFAULT_MESSAGE = (
#         "%(cmd)s returned non-zero exit code: ret:%(returncode)i, "
#         "stdout: %(stdout)s, stderr: %(stderr)s")
#     DEFAULT_MESSAGE = (
#         "Timeout failure on %(func_name)s after %(num_attempts)s attempts. "
#         "Initial timeout: %(initial_timeout)s, final timeout: "
#         "%(final_timeout)s.")
#     DEFAULT_MESSAGE = (
#         "Files to be validated not found in base directory.")
#     DEFAULT_MESSAGE = (
#         "No packages were updated since last commit.")
#     def __init__(self, message=None, **kwargs):
# 
# Path: lib/log_helper.py
# class LogHelper(object):
#     def __init__(self, log_file_path=None, verbose=False, rotate_size=0):
# 
# Path: lib/utils.py
# def is_package_installed(package_name):
#     """
#     Checks if a RPM package is installed
# 
#     Args:
#         package_name (str): package name
# 
#     Returns:
#         bool: if RPM package is installed
#     """
# 
#     cmd = "rpm -q --whatprovides %s" % package_name
#     try:
#         run_command(cmd, shell=True)
#     except exception.SubprocessError as e:
#         # rpm returns 1 when search string is not found and other non-zero values
#         # if an error occurred
#         #pylint: disable=no-member
#         if e.returncode == 1:
#             return False
#         else:
#             raise
# 
#     return True
# 
# Path: lib/utils.py
# def recursive_glob(directory, pattern):
#     """
#     Find all files matching a pattern according to the rules used by Linux shell
# 
#     Args:
#         directory (str): searched directory
#         pattern (str): glob pattern
#     """
# 
#     matches = []
# 
#     for root, _, filenames in os.walk(directory, onerror=base_directory_not_found_error):
#         for filename in fnmatch.filter(filenames, pattern):
#             matches.append(os.path.join(root, filename))
# 
#     return matches
# 
# Path: lib/utils.py
# def run_command(cmd, **kwargs):
#     """
#     Run command, wait for it to finish and read its output.
# 
#     Args:
#         cmd (str): command string
#         kwargs (dict): extra parameters passed to subprocess.Popen
# 
#     Returns:
#         str: command standard output
#     """
#     LOG.debug("Command: %s" % cmd)
#     shell = kwargs.pop('shell', True)
#     success_return_codes = kwargs.pop('success_return_codes', [0])
# 
#     process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
#                                stderr=subprocess.PIPE, shell=shell, **kwargs)
#     output, error_output = process.communicate()
# 
#     LOG.debug("stdout: %s" % output)
#     LOG.debug("stderr: %s" % error_output)
# 
#     if process.returncode not in success_return_codes:
#         raise exception.SubprocessError(cmd=cmd, returncode=process.returncode,
#                                         stdout=output, stderr=error_output)
# 
#     return output


import argparse
import os
import sys
import logging
from lib import exception
from lib import log_helper
from lib.utils import is_package_installed
from lib.utils import recursive_glob
from lib.utils import run_command
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


repo_root_dir = os.path.realpath(os.path.join(
    os.path.dirname(__file__), os.pardir))
sys.path.insert(0, repo_root_dir)


def validate_rpm_spec(spec_file_path):
    """
    Validate RPM specification file

    Args:
        spec_file_path (str): RPM specification file path

    Returns:
        bool: if RPM specification file is valid
    """

    try:
        LOG.info("Verifying file %s" % spec_file_path)
        run_command("rpmlint -f .rpmlint -v %s" % spec_file_path)
    except exception.SubprocessError as e:
        #pylint: disable=no-member

# Path: lib/exception.py
# class BaseException(Exception):
# class RequiredParameterMissing(BaseException):
# class DistributionError(BaseException):
# class DistributionDetectionError(DistributionError):
# class DistributionNotSupportedError(DistributionError):
# class DistributionVersionNotSupportedError(DistributionError):
# class PackageError(BaseException):
# class PackageSpecError(PackageError):
# class PackageDescriptorError(PackageError):
# class PackageDirectoryIsEmpty(PackageError):
# class RepositoryError(BaseException):
# class SubprocessError(BaseException):
# class TimeoutError(BaseException):
# class FilesToValidateNotFound(BaseException):
# class NoPackagesUpdated(BaseException):
#     DEFAULT_MESSAGE = "Failed to build packages"
#     DEFAULT_MESSAGE = "Required parameter '%(parameter)s' is missing"
#     DEFAULT_MESSAGE = "Distribution not Supported"
#     DEFAULT_MESSAGE = "Failed to detect system's GNU/Linux distribution"
#     DEFAULT_MESSAGE = "%(distribution)s distribution is not supported"
#     DEFAULT_MESSAGE = "%(distribution)s version %(version)s is not supported"
#     DEFAULT_MESSAGE = "Failed to gather %(package)s's information"
#     DEFAULT_MESSAGE = (
#         "%(package)s's spec for %(distro)s %(distro_version)s not Found.")
#     DEFAULT_MESSAGE = "Missing data in %(package)s's YAML descriptor"
#     DEFAULT_MESSAGE = "No packages to build. Packages directory is empty."
#     DEFAULT_MESSAGE = (
#         "Failed to setup %(repo_name)s's repository at %(repo_path)s.")
#     DEFAULT_MESSAGE = (
#         "%(cmd)s returned non-zero exit code: ret:%(returncode)i, "
#         "stdout: %(stdout)s, stderr: %(stderr)s")
#     DEFAULT_MESSAGE = (
#         "Timeout failure on %(func_name)s after %(num_attempts)s attempts. "
#         "Initial timeout: %(initial_timeout)s, final timeout: "
#         "%(final_timeout)s.")
#     DEFAULT_MESSAGE = (
#         "Files to be validated not found in base directory.")
#     DEFAULT_MESSAGE = (
#         "No packages were updated since last commit.")
#     def __init__(self, message=None, **kwargs):
# 
# Path: lib/log_helper.py
# class LogHelper(object):
#     def __init__(self, log_file_path=None, verbose=False, rotate_size=0):
# 
# Path: lib/utils.py
# def is_package_installed(package_name):
#     """
#     Checks if a RPM package is installed
# 
#     Args:
#         package_name (str): package name
# 
#     Returns:
#         bool: if RPM package is installed
#     """
# 
#     cmd = "rpm -q --whatprovides %s" % package_name
#     try:
#         run_command(cmd, shell=True)
#     except exception.SubprocessError as e:
#         # rpm returns 1 when search string is not found and other non-zero values
#         # if an error occurred
#         #pylint: disable=no-member
#         if e.returncode == 1:
#             return False
#         else:
#             raise
# 
#     return True
# 
# Path: lib/utils.py
# def recursive_glob(directory, pattern):
#     """
#     Find all files matching a pattern according to the rules used by Linux shell
# 
#     Args:
#         directory (str): searched directory
#         pattern (str): glob pattern
#     """
# 
#     matches = []
# 
#     for root, _, filenames in os.walk(directory, onerror=base_directory_not_found_error):
#         for filename in fnmatch.filter(filenames, pattern):
#             matches.append(os.path.join(root, filename))
# 
#     return matches
# 
# Path: lib/utils.py
# def run_command(cmd, **kwargs):
#     """
#     Run command, wait for it to finish and read its output.
# 
#     Args:
#         cmd (str): command string
#         kwargs (dict): extra parameters passed to subprocess.Popen
# 
#     Returns:
#         str: command standard output
#     """
#     LOG.debug("Command: %s" % cmd)
#     shell = kwargs.pop('shell', True)
#     success_return_codes = kwargs.pop('success_return_codes', [0])
# 
#     process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
#                                stderr=subprocess.PIPE, shell=shell, **kwargs)
#     output, error_output = process.communicate()
# 
#     LOG.debug("stdout: %s" % output)
#     LOG.debug("stderr: %s" % error_output)
# 
#     if process.returncode not in success_return_codes:
#         raise exception.SubprocessError(cmd=cmd, returncode=process.returncode,
#                                         stdout=output, stderr=error_output)
# 
#     return output


# Path: scripts/validate_rpm_specs.py
import argparse
import os
import sys
import logging
from lib import exception
from lib import log_helper
from lib.utils import is_package_installed
from lib.utils import recursive_glob
from lib.utils import run_command

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


repo_root_dir = os.path.realpath(os.path.join(
    os.path.dirname(__file__), os.pardir))
sys.path.insert(0, repo_root_dir)


def validate_rpm_spec(spec_file_path):
    """
    Validate RPM specification file

    Args:
        spec_file_path (str): RPM specification file path

    Returns:
        bool: if RPM specification file is valid
    """

    try:
        LOG.info("Verifying file %s" % spec_file_path)
        run_command("rpmlint -f .rpmlint -v %s" % spec_file_path)
    except exception.SubprocessError as e:
        #pylint: disable=no-member

        LOG.exception("validation of RPM specification file %s failed, output: %s" % (spec_file_path, e.stdout))