#!/usr/bin/python
#
# Copyright (c) 2013 SUSE LLC
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#

import sys
from spacewalk.server import rhnSQL
from spacewalk.common.rhnConfig import initCFG
from check_suma_common import *

#############################################################################

if __name__ == '__main__':
    systemid = get_system_ID_by_name(check_one_arg(sys.argv))
    sql = rhnSQL.prepare("""SELECT DISTINCT E.id
                            FROM rhnErrata E, rhnServerNeededErrataCache SNEC
                            WHERE EXISTS
                            (SELECT server_id FROM rhnUserServerPerms USP
                            WHERE USP.server_id = :sid)
                            AND SNEC.server_id = :sid
                            AND SNEC.errata_id = E.id
                            AND E.advisory_type = 'Security Advisory'""")
    sql.execute(sid = systemid)
    patches = sql.fetchall_dict()
    if patches:
        resultExit(2, "CRITICAL: %d critical patch(es) pending" % len(patches))
    else:
        sql = rhnSQL.prepare("""SELECT DISTINCT E.id
                                FROM rhnErrata E, rhnServerNeededErrataCache SNEC
                                WHERE EXISTS
                                (SELECT server_id FROM rhnUserServerPerms USP
                                WHERE USP.server_id = :sid)
                                AND SNEC.server_id = :sid
                                AND SNEC.errata_id = E.id""")
        sql.execute(sid = systemid)
        patches = sql.fetchall_dict()
        if patches:
            resultExit(1, "WARNING: %d patch(es) pending" % len(patches))
        else:
            resultExit(0, "OK: System is up to date")
