import glob
import os
import sys
import re
import fnmatch
from shutil import copyfile
import time
#os.environ['LIBPATH'] = '/usr/opt/rpm/lib:/opt/freeware/lib:/lib'
try:
    import yum
except ImportError:
    sys.exit(1)
try:
    import sqlite3 as sqlite
    is_sqlite3 = 1
except ImportError:
    import sqlite
    is_sqlite3 = 0

file_exists=0
if os.path.exists('/var/lib/yum/history'):
    for file in os.listdir('/var/lib/yum/history'):
        if fnmatch.fnmatch(file,  'history-*.sqlite'):
            h_file = file
            file_exists = 1
else:
    print "/var/lib/yum/history path doesn't exists, nothing to migrate yet."
    sys.exit(1)

if file_exists == 0:
    print "History file doesn't exists, nothing to migrate yet."
    sys.exit (1)

# Take backup of existing history file.
t = time.localtime()
ymdhms = str(t.tm_year)+str(t.tm_mon)+str(t.tm_mday)+str(t.tm_hour)+str(t.tm_min)+str(t.tm_sec)
copyfile ('/var/lib/yum/history/'+h_file, '/var/lib/yum/history/'+h_file+"_yum_bak_"+ymdhms)

con = sqlite.connect ("/var/lib/yum/history/"+h_file)
cur = con.cursor()
try:
    cur.execute (''' SELECT count(pkgtupid)  FROM pkg_yumdb ''')
    t_exists = True
except (sqlite.OperationalError, sqlite.DatabaseError), e:
    if e.args[0].startswith('no such table'):
        t_exists = False
    else:
        riase
if t_exists == False:
     cur.execute  ("CREATE TABLE pkg_yumdb (\
         pkgtupid INTEGER NOT NULL REFERENCES pkgtups,\
         yumdb_key TEXT NOT NULL,\
         yumdb_val TEXT NOT NULL)")
     cur.execute("CREATE INDEX i_pkgkey_yumdb ON pkg_yumdb (pkgtupid, yumdb_key)")

yb = yum.YumBase()
for pkg in sorted(yb.rpmdb.returnPackages('info')):
    for ykey in sorted(pkg.yumdb_info):
        if ykey == 'from_repo':
            yumdb_from_repo = getattr(pkg.yumdb_info, ykey)
        if ykey == 'reason':
            yumdb_reason = getattr(pkg.yumdb_info, ykey)
    (n, a, e, v, r) = pkg.pkgtup
    nvra = ['','','','' ]
    nvra[0] = n
    nvra[1] = v
    nvra[2] = r
    nvra[3] = a
    if is_sqlite3 == 1:
        cur.execute ("SELECT pkgtupid from pkgtups where\
                     name=? and version=? and release=? and arch=?", nvra)
    else:
        cur.execute ("SELECT pkgtupid from pkgtups where\
                      name=%s and version=%s and release=%s and arch=%s", nvra)
    pkg_row = cur.fetchone()
    if pkg_row is not None:
        pkg_tupid = pkg_row[0]
        repo_vals = ['', '', '']
        repo_vals[0] = pkg_tupid
        try:
            yumdb_reason
            yumdb_from_repo
        except NameError:
            print '** Can NOT process ' + str(pkg) + ' becuase it does not have a yumdb reason or yumdb_from_repo'
            continue
        repo_vals[1] = 'from_repo'
        repo_vals[2] = yumdb_from_repo
        reason_vals = ['', '', '']
        reason_vals[0] = pkg_tupid
        reason_vals[1] = 'reason'
        reason_vals[2] = yumdb_reason
        if is_sqlite3 == 1:
            cur.execute ("INSERT INTO pkg_yumdb (pkgtupid, yumdb_key, yumdb_val)\
                         VALUES (?, ?, ?)", repo_vals)
            cur.execute ("INSERT INTO pkg_yumdb (pkgtupid, yumdb_key, yumdb_val)\
                         VALUES (?, ?, ?)", reason_vals)
        else:
            cur.execute ("INSERT INTO pkg_yumdb (pkgtupid, yumdb_key, yumdb_val)\
                         VALUES (%s, %s, %s)", repo_vals)
            cur.execute ("INSERT INTO pkg_yumdb (pkgtupid, yumdb_key, yumdb_val)\
                         VALUES (%s, %s, %s)", reason_vals)
con.commit()
con.close()
