#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import sys
import rpm
import argparse

def CompareWithRPMDB(args):
    rpmfile = str(args.rpmfile)
    dbpath = str(args.dbpath)
    old_package_file = dbpath + "/Packages"
    packagedb_file = dbpath + "/Packages.db"
    indexdb_file = dbpath + "/Index.db"
    #check input files
    if os.path.isfile(packagedb_file):
        if not os.path.isfile(indexdb_file):
            print("rpm database: %s is incorrect, please check." % indexdb_file)
            return 1
    elif not os.path.isfile(old_package_file):
        print("rpm database: %s is incorrect, please check." % (old_package_file))
        return 1

    if not os.path.isfile(rpmfile):
        print("rpmfile: %s not found, please check." % rpmfile)
        return 1

    try:
        #get rpmfile info
        ts_rpmfile = rpm.TransactionSet()
        ts_rpmfile.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
        fd = os.open(rpmfile, os.O_RDONLY)
        header_rpmfile = ts_rpmfile.hdrFromFdno(fd)
        os.close(fd)

        #get info from rpmdb
        rpm.addMacro("_dbpath", dbpath)
        ts_dbpath = rpm.TransactionSet()
        ts_dbpath.openDB()
        ts_dbpath.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
        mi = ts_dbpath.dbMatch(rpm.RPMTAG_NAME, header_rpmfile[rpm.RPMTAG_NAME])
        ts_dbpath.closeDB()
        rpm.delMacro("_dbpath")
        #not found package name in rpmdb, return 13
        if not mi:
            rc = 13
        else:
            for header_dbpath in mi:
                #if rpm name and arch is matched, compare it and return result
                if header_dbpath is not None and header_dbpath[rpm.RPMTAG_ARCH]==header_rpmfile[rpm.RPMTAG_ARCH]:
                    rc = rpm.labelCompare((str(header_dbpath[rpm.RPMTAG_EPOCH] or None),
                        str(header_dbpath[rpm.RPMTAG_VERSION]), str(header_dbpath[rpm.RPMTAG_RELEASE])),
                        (str(header_rpmfile[rpm.RPMTAG_EPOCH] or None), str(header_rpmfile[rpm.RPMTAG_VERSION]),
                        str(header_rpmfile[rpm.RPMTAG_RELEASE])))
                    if rc > 0:
                        rc = 11
                    elif rc < 0:
                        rc = 12
                    break
                #if rpm not found in rpmdb or arch is not matched, mark rc = 13, and goto loop
                else:
                    rc = 13
                    continue
    except Exception as e:
        print("compare version of %s in %s failed, exception: %s" %(rpmfile, dbpath, e))
        return 1

    return rc

def CompareWithRPMName(args):
    rpmfile1 = str(args.rpmfile1)
    rpmfile2 = str(args.rpmfile2)

    #check input files
    if not os.path.isfile(rpmfile1):
        print("rpmfile: %s not found, please check." % rpmfile1)
        return 1

    if not os.path.isfile(rpmfile2):
        print("rpmfile: %s not found, please check." % rpmfile2)
        return 1

    try:
        #get rpmfile1 info
        ts_rpmfile1 = rpm.TransactionSet()
        ts_rpmfile1.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
        fd = os.open(rpmfile1, os.O_RDONLY)
        header_rpmfile1 = ts_rpmfile1.hdrFromFdno(fd)
        os.close(fd)

        #get rpmfile2 info
        ts_rpmfile2 = rpm.TransactionSet()
        ts_rpmfile2.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
        fd = os.open(rpmfile2, os.O_RDONLY)
        header_rpmfile2 = ts_rpmfile2.hdrFromFdno(fd)
        os.close(fd)

        if header_rpmfile2[rpm.RPMTAG_ARCH]==header_rpmfile1[rpm.RPMTAG_ARCH] and header_rpmfile2[rpm.RPMTAG_NAME]==header_rpmfile1[rpm.RPMTAG_NAME]:
            rc = rpm.labelCompare((str(header_rpmfile1[rpm.RPMTAG_EPOCH]) or None, str(header_rpmfile1[rpm.RPMTAG_VERSION]) or None, str(header_rpmfile1[rpm.RPMTAG_RELEASE]) or None),
                (str(header_rpmfile2[rpm.RPMTAG_EPOCH]) or None, str(header_rpmfile2[rpm.RPMTAG_VERSION]) or None, str(header_rpmfile2[rpm.RPMTAG_RELEASE]) or None))
            if rc > 0:
                rc = 11
            elif rc < 0:
                rc = 12
        else:
            print("name and arch of rpm package error.")
            return 1
    except Exception as e:
        print("compare version failed, exception: %s" % e)
        return 1

    return rc

def main():
    parser = argparse.ArgumentParser(description='Compare rpm version.')
    subparsers = parser.add_subparsers()

    # create the parser for the "query" command
    parser_query = subparsers.add_parser('query',
                       help='compare rpm version with rpm database')
    parser_query.add_argument('--dbpath', type=str, default="/var/lib/rpm",
                       help='the path of rpm database')
    parser_query.add_argument('rpmfile',  type=str,
                       help='rpm package file')
    parser_query.set_defaults(func=CompareWithRPMDB)

    # create the parser for the "compare" command
    parser_compare = subparsers.add_parser('compare',
                       help='compare rpm version with rpm package')
    parser_compare.add_argument('rpmfile1', type=str,
                       help='rpm package file')
    parser_compare.add_argument('rpmfile2', type=str,
                       help='rpm package file')
    parser_compare.set_defaults(func=CompareWithRPMName)

    args = parser.parse_args()
    ret = args.func(args)
    sys.exit(ret)
if __name__ == "__main__":
    main()
