#!/usr/bin/env python3
#
# Copyright (C) 2014        Alex Damian
#
# SPDX-License-Identifier: GPL-2.0-only
#
# This file re-uses code spread throughout other Bitbake source files.
# As such, all other copyrights belong to their own right holders.
#

"""
This command takes a filename as a single parameter. The filename is read
as a build eventlog, and the ToasterUI is used to process events in the file
and log data in the database
"""

import os
import sys
import json
import pickle
import codecs
import warnings
warnings.simplefilter("default")

from collections import namedtuple

# mangle syspath to allow easy import of modules
from os.path import join, dirname, abspath
sys.path.insert(0, join(dirname(dirname(abspath(__file__))), 'lib'))

import bb.cooker
from bb.ui import toasterui
from bb.ui import eventreplay

def main(argv):
    with open(argv[-1]) as eventfile:
        # load variables from the first line
        variables = None
        while line := eventfile.readline().strip():
            try:
                variables = json.loads(line)['allvariables']
                break
            except (KeyError, json.JSONDecodeError):
                continue
        if not variables:
            sys.exit("Cannot find allvariables entry in event log file %s" % argv[-1])
        eventfile.seek(0)
        params = namedtuple('ConfigParams', ['observe_only'])(True)
        player = eventreplay.EventPlayer(eventfile, variables)

        return toasterui.main(player, player, params)

# run toaster ui on our mock bitbake class
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: %s <event file>" % os.path.basename(sys.argv[0]))
        sys.exit(1)

    sys.exit(main(sys.argv))
