#!/usr/bin/python -u
#
# Copyright (c) 2008--2013 Red Hat, Inc.
#
# 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.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#


import sys
try:
    import os
    from os.path import exists, join
except KeyboardInterrupt:
    sys.stderr.write("\nUser interrupted process.\n")
    sys.exit(0)


def errAndExit(errno, msg):
    sys.stderr.write(msg+'\n')
    sys.exit(errno)


# figure out import path
_LIBPATH = ""
for p in ["/var/www/rhns", "/usr/share/rhn"]:
    if exists(p) and exists(join(p, 'server')) and exists(join(p, 'common')):
        _LIBPATH = p
if _LIBPATH not in sys.path:
    sys.path.append(_LIBPATH)


try:
    from spacewalk.server import rhnSQL
except KeyboardInterrupt:
    sys.stderr.write("\nUser interrupted process.\n")
    sys.exit(0)


if __name__ == '__main__':
    rhnSQL.initDB()

    try:
        h = rhnSQL.prepare("""
                SELECT evr_t_as_vre_simple(PE.evr) as evrsimple
                  FROM rhnPackageEVR PE, rhnVersionInfo RVI, rhnPackageName PN
                 WHERE RVI.label = 'schema'
                   AND RVI.name_id = PN.id
                   AND RVI.evr_id = PE.id
                """)
        h.execute()
        row = h.fetchone_dict()
        if row:
            print row['evrsimple']
    except KeyboardInterrupt:
        sys.stderr.write("\nUser interrupted process.\n")
        sys.exit(0)
    except (rhnSQL.SQLError, rhnSQL.SQLSchemaError, rhnSQL.SQLConnectError), e:
        # really a stub for better exception handling in the future.
        sys.stderr.write("SQL error occurred, traceback follows...\n")
        raise


