# Common definitions for CVE database fetching native recipes
SUMMARY = "Updates the NVD CVE database"
LICENSE = "MIT"

INHIBIT_DEFAULT_DEPS = "1"

inherit native

deltask do_patch
deltask do_configure
deltask do_compile
deltask do_install
deltask do_populate_sysroot

# CVE database update interval, in seconds. By default: once a day (23*60*60).
# Use 0 to force the update
# Use a negative value to skip the update
CVE_DB_UPDATE_INTERVAL ?= "82800"

CVE_CHECK_DB_DLDIR_FILE ?= "${DL_DIR}/CVE_CHECK2/${CVE_CHECK_DB_FILENAME}"
CVE_CHECK_DB_DLDIR_LOCK ?= "${CVE_CHECK_DB_DLDIR_FILE}.lock"
CVE_CHECK_DB_TEMP_FILE ?= "${CVE_CHECK_DB_FILE}.tmp"

python() {
    if not bb.data.inherits_class("cve-check", d):
        raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
}

python do_fetch() {
    """
    Update NVD database
    """
    import bb.utils
    import bb.progress
    import shutil
    import time

    bb.utils.export_proxies(d)

    db_file = d.getVar("CVE_CHECK_DB_DLDIR_FILE")
    db_dir = os.path.dirname(db_file)
    db_tmp_file = d.getVar("CVE_CHECK_DB_TEMP_FILE")

    cleanup_db_download(db_tmp_file)
    # By default let's update the whole database (since time 0)
    database_time = 0

    # The NVD database changes once a day, so no need to update more frequently
    # Allow the user to force-update
    update_interval = int(d.getVar("CVE_DB_UPDATE_INTERVAL"))
    if update_interval < 0:
        bb.note("CVE database update skipped")
        if not os.path.exists(db_file):
            bb.error("CVE database %s not present, database fetch/update skipped" % db_file)
        return

    if os.path.exists(db_file):
        database_time = get_mtime_timestamp_from(db_file)
        curr_time = time.time()
        bb.note("Current time: %s; DB time: %s" % (time.ctime(curr_time), time.ctime(database_time)))
        if curr_time < database_time:
            bb.warn("Database time is in the future, force DB update")
            database_time = 0
        elif curr_time - database_time < update_interval:
            bb.note("CVE database recently updated, skipping")
            return

    if bb.utils.to_boolean(d.getVar("BB_NO_NETWORK")):
        bb.error("BB_NO_NETWORK attempted to disable fetch, this recipe uses CVE_DB_UPDATE_INTERVAL to control download, set to '-1' to disable fetch or update")

    bb.utils.mkdirhier(db_dir)
    bb.utils.mkdirhier(os.path.dirname(db_tmp_file))
    if os.path.exists(db_file):
        shutil.copy2(db_file, db_tmp_file)

    if update_db_file(db_tmp_file, d, database_time):
        # Update downloaded correctly, can swap files
        shutil.move(db_tmp_file, db_file)
    else:
        # Update failed, do not modify the database
        bb.warn("CVE database update failed")
        os.remove(db_tmp_file)
}
do_fetch[lockfiles] += "${CVE_CHECK_DB_DLDIR_LOCK}"
do_fetch[file-checksums] = ""
do_fetch[vardeps] = ""
do_fetch[nostamp] = "1"

python do_unpack() {
    import shutil
    shutil.copyfile(d.getVar("CVE_CHECK_DB_DLDIR_FILE"), d.getVar("CVE_CHECK_DB_FILE"))
}
do_unpack[lockfiles] += "${CVE_CHECK_DB_DLDIR_LOCK} ${CVE_CHECK_DB_FILE_LOCK}"

def cleanup_db_download(db_tmp_file):
    """
    Cleanup the download space from possible failed downloads
    """

    # Clean-up the temporary file downloads, we can remove both journal
    # and the temporary database
    if os.path.exists("{0}-journal".format(db_tmp_file)):
        os.remove("{0}-journal".format(db_tmp_file))
    if os.path.exists(db_tmp_file):
        os.remove(db_tmp_file)


def get_mtime_timestamp_from(db_file):
    """
    Resolve the time when the CVE database was previously updated
    """
    import datetime
    import sqlite3

    conn = sqlite3.connect(db_file)
    curs = conn.cursor()
    res = curs.execute("select TIMESTAMP from MTIME order by TIMESTAMP desc limit 1;")
    latest = res.fetchone()[0]
    latest = datetime.datetime.strptime(latest, '%Y-%m-%dT%H:%M:%S.%f+00:00')
    latest = latest.astimezone(tz=datetime.timezone.utc)
    curs.close()
    conn.close()
    return latest.timestamp()


def initialize_db(conn):
    with conn:
        c = conn.cursor()

        c.execute("CREATE TABLE IF NOT EXISTS MTIME (TIMESTAMP INT)")

        c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")

        c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
            SCOREV2 TEXT, SCOREV3 TEXT, SCOREV4 TEXT, MODIFIED INTEGER, VECTOR TEXT, VECTORSTRING TEXT)")

        c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
            VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
            VERSION_END TEXT, OPERATOR_END TEXT)")
        c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")

        c.close()


EXCLUDE_FROM_WORLD = "1"
