#
# Copyright (C) 2017  Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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/>.
#
import configparser
import grp
import os
from pylorax.sysutils import joinpaths
[docs]class ComposerConfig(configparser.SafeConfigParser):
[docs]    def get_default(self, section, option, default):
        try:
            return self.get(section, option)
        except configparser.Error:
            return default  
[docs]def make_dnf_dirs(conf):
    """Make any missing dnf directories
    :param conf: The configuration to use
    :type conf: ComposerConfig
    :returns: None
    """
    for p in ["dnf_conf", "repo_dir", "cache_dir", "dnf_root"]:
        p_dir = os.path.abspath(conf.get("composer", p))
        if p == "dnf_conf":
            p_dir = os.path.dirname(p_dir)
        if not os.path.isdir(p_dir):
            os.makedirs(p_dir) 
[docs]def make_queue_dirs(conf, gid):
    """Make any missing queue directories
    :param conf: The configuration to use
    :type conf: ComposerConfig
    :param gid: Group ID that has access to the queue directories
    :type gid: int
    :returns: list of errors
    :rtype: list of str
    """
    errors = []
    lib_dir = conf.get("composer", "lib_dir")
    for p in ["queue/run", "queue/new", "results"]:
        p_dir = joinpaths(lib_dir, p)
        if not os.path.exists(p_dir):
            orig_umask = os.umask(0)
            os.makedirs(p_dir, 0o771)
            os.chown(p_dir, 0, gid)
            os.umask(orig_umask)
        else:
            p_stat = os.stat(p_dir)
            if p_stat.st_mode & 0o006 != 0:
                errors.append("Incorrect permissions on %s, no o+rw permissions are allowed." % p_dir)
            if p_stat.st_gid != gid or p_stat.st_uid != 0:
                gr_name = grp.getgrgid(gid).gr_name
                errors.append("%s should be owned by root:%s" % (p_dir, gr_name))
    return errors