#!/usr/bin/env python3
#
# Copyright 2013-present Barefoot Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
# p4c is supposed to work in two environments:
#  - installed mode: in ${prefix}/bin, with artifacts in ${datadir}/p4c/*
#  - developer mode: in the build dir with artifacts rooted also in the build dir
install_dir = os.path.abspath(os.path.dirname(os.path.realpath(sys.argv[0])))
if not os.path.exists(os.path.join(install_dir, 'p4c_src')):
    # this is the installed configuration
    build_type = "INSTALLED"
    artifacts_dir = '${prefix}/share'
    if artifacts_dir == '${prefix}/share':
        # datadir based on prefix
        if '/usr' != '${prefix}':
            bin2prefix = os.path.relpath('/usr', '/usr/bin')
        else:
            bin2prefix = '..'
        artifacts_dir = os.path.normpath(os.path.join(install_dir, bin2prefix, "share/p4c"))
    else:
        # explicit datadir. add package name
        artifacts_dir = os.path.join(artifacts_dir, 'p4c')
else:
    build_type = "DEVELOPER"
    artifacts_dir = install_dir

sys.path.insert(1, artifacts_dir)
os.environ['P4C_BUILD_TYPE'] = build_type
os.environ['P4C_BIN_DIR'] = install_dir
os.environ['P4C_CFG_PATH'] = os.path.join(artifacts_dir, "p4c_src")
os.environ['P4C_16_INCLUDE_PATH'] = os.path.realpath(os.path.join(artifacts_dir, "p4include"))
os.environ['P4C_14_INCLUDE_PATH'] = os.path.realpath(os.path.join(artifacts_dir, "p4_14include"))

from p4c_src.main import main
from p4c_src.main import set_version

set_version("1.2.5.9 (SHA:  BUILD: RelWithDebInfo)")

if __name__ == '__main__':
    main()
