#!/usr/bin/python3
import dnf
import sys
import sqlite3

if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("Please pass the name of the dnf database cache file as the first argument")
        print("e.g.: {} <cache database file>".format(sys.argv[0]))
        sys.exit(1)

    OUTPUT_FILE = sys.argv[1]

    print("Loading DNF metadata...")
    with dnf.Base() as base:
        base.read_all_repos()
        base.fill_sack()
        q = base.sack.query()

    q_available = q.available()
    available_packages = q_available.run()
    data = [(pkg.name, pkg.version, pkg.arch, pkg.summary, pkg.reponame, pkg.license, pkg.description) for pkg in available_packages]
    data.sort()

    print("Creating database file...")
    with sqlite3.connect(OUTPUT_FILE) as conn:
        cursor = conn.cursor()
        cursor.execute("CREATE TABLE available (pkg text, version text, arch text, summary text, reponame text, license text, description text)")
        cursor.execute("CREATE INDEX pkg_available ON available(pkg)")
        cursor.execute("CREATE INDEX pkg_description ON available(description)")
        print("Inserting data...")
        cursor.executemany("INSERT INTO available VALUES (?, ?, ?, ?, ?, ?, ?)", data)
        conn.commit()
    print("Done")
