#!/usr/bin/env python3
# ebitbake
#
# Copyright (C) 2003, 2004  Chris Larson
# Copyright (C) 2003, 2004  Phil Blundell
# Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
# Copyright (C) 2005        Holger Hans Peter Freyther
# Copyright (C) 2005        ROAD GmbH
# Copyright (C) 2006        Richard Purdie
# Copyright (C) 2018-2019   Electric Cloud, Inc.
# Copyright (C) 2019-2023   CloudBees, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import os
import sys

from ebb import *

if sys.getfilesystemencoding().lower() != "utf-8":
    sys.exit("""\
ERROR: Please use a locale setting which supports UTF-8.
Python can't change the filesystem locale after loading so we
need UTF-8 when Python starts or things won't work.""")

def main():
    os.environ['PATH'] = ':'.join([
        os.path.dirname(sys.argv[0]),
        os.path.abspath(os.path.join(os.path.dirname(
            sys.argv[0]), "..", "lib", "ebitbake")),
        os.environ['PATH']])
    for arg in sys.argv:
        if (arg.startswith("--ebitbake-info")
            or arg.startswith("--eb-info")):
            bb, bb_bin_dir, bb_lib_dir, buildname = ebitbake_init()
            print("Script: {}".format(sys.argv[0]))
            print("Module: {}".format(bb))
            print("Binary directory: {}".format(bb_bin_dir))
            print("Library directory: {}".format(bb_lib_dir))
            print("Minimum supported version: {} {}".format(
                MIN_VERSION, parse_version(MIN_VERSION)))
            print("Maximum supported version: {} {}".format(
                MAX_VERSION, parse_version(MAX_VERSION)))
            print("Actual bitbake version: {}".format(ebitbake_get_version()))
            ok = True
            versionOk = ebitbake_check_version(MIN_VERSION, MAX_VERSION)
            if not versionOk:
                ok = False
            print()
            print("Version check: {}".format("Success" if versionOk else "FAILURE"))
            configOk = ebitbake_check_configuration()
            if not configOk:
                ok = False
            print("Configuration check: {}".format(
                "Success" if configOk else "FAILURE"))
            try:
                PackageOptions.validate(DEFAULT_OPTIONS_JSON)
                print("Default package options JSON validation: Success")
                optionsOk = True
            except Exception as e:
                print("Default package options JSON validation: FAILURE: {}".format(e))
                ok = optionsOk = False
            print("Would-be build name: {}".format(buildname))
            if not ok:
                print()
                print("ERROR: Some checks failed")
            sys.exit(0 if ok else 1)
        elif (arg.startswith("--ebitbake-checkopt")
            or arg.startswith("--eb-checkopt")):
            ok = True
            try:
                PackageOptions.validate(DEFAULT_OPTIONS_JSON)
                print("Default package options JSON validated properly")
            except Exception as e:
                print("ERROR: Validation failed: {}".format(e))
                ok = False
            sys.exit(0 if ok else 1)
        elif (arg.startswith("--ebitbake-showopt")
            or arg.startswith("--eb-showopt")):
            sys.stdout.write(DEFAULT_OPTIONS_JSON)
            sys.exit(0)
        elif (arg.startswith("--ebitbake-patch")
              or arg.startswith("--eb-patch")):
            ebitbake_static_patch()
            sys.exit(0)
    bb, bb_bin_dir, bb_lib_dir, buildname = ebitbake_init()
    ebitbake_static_patch()
    ebitbake_check_version(MIN_VERSION, MAX_VERSION, complain=True)

    from bb import cookerdata
    from bb.main import bitbake_main, BitBakeConfigParameters, BBMainException
    from bb import data_smart

    bitbakedir = os.path.dirname(bb_bin_dir)
    pokydir = os.path.dirname(bitbakedir)
    try:
        prune_confs() # get rid of any excess before adding more
        sys.argv.append("-r")
        sys.argv.append(write_build_pre_config(pokydir, buildname))

        print("BUILDNAME = {}".format(buildname))
        ebitbake_precreate_dirs()
        sys.exit(bitbake_main(BitBakeConfigParameters(sys.argv),
                              cookerdata.CookerConfiguration()))
    except BBMainException as e:
        sys.exit(e)
    except bb.BBHandledException:
        sys.exit(1)
    except Exception:
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == '__main__': main()
