# Copyright 2019-2022, 2025 NXP
# SPDX-License-Identifier: BSD-3-Clause

"""
Copyright 2015-2022 Freescale Semiconductor, Inc.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Freescale Semiconductor nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

This software is provided by Freescale Semiconductor "as is" and any
express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall Freescale Semiconductor be liable for any
direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and
on any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of
this software, even if advised of the possibility of such damage.

"""

import gdb   # @UnresolvedImport  # pylint: disable=F0401
import os
import signal
import time
import os.path
import sys
import importlib

from subprocess import Popen, PIPE
from rsdk_test.scripts.utils import gdb_execute
from flash.scripts.hooks import uninstall_hook_quit_cmd

GTA_INSTALL_DIR = ''.join([os.path.dirname(os.path.realpath(__file__)),
                          '/', '../../../gta/'])
GDB_EXT_DIR = ''.join([os.path.dirname(os.path.realpath(__file__)),
                          '/', '../../../gdb_extensions/'])


#module private instance
_gta_proc = None
#_ddr_prompt ='dsDDR'


def internal_start(args):
    """
        Board initialization script
    """
    print('Starting board initialization services...')
    if internal_initialize_target(args) is False:
        return False 
    ###################################################################
    ######### 
    ###################################################################
    print("SoC Initialized")

        
def lax_specific_gdb_init():
    
    try:
        gdb_execute('set endian little')
        gdb_execute('set stack-cache off')
        gdb_execute('set code-cache off')
        gdb_execute('set interactive-mode off')
        
    except gdb.GdbError as e:
        print(str(e))
        

def internal_initialize_target(args):
    """
        Initialize target
    """
    print('Initializing target...')

    #adding set of commands
    if args.no_soc_init is False:
        board_init_path = args.init
        board_init_script = os.path.basename(board_init_path)
       
        #check if file exists
        if os.path.isfile(board_init_path) is True:
            print('Running init script %s' % board_init_path)
            try:
                fname = os.path.basename(board_init_path)
                path = os.path.dirname(board_init_path)
                sys.path.append(path)
            
                DbgInit = importlib.import_module(fname[:-3])                
                DbgInit.board_init()
                DbgInit.core_init()
                
                lax_specific_gdb_init()
				
            except gdb.GdbError as e:
                print(str(e))
                print('I-ERROR: fail to initialize target')
                return False
            print('Initialized board with script %s.' % board_init_script)
        else:
            print('D-ERROR: can\'t find init script %s' % board_init_path)
            return False
        return True
    else:
        gdb_execute('monitor halt')
        lax_specific_gdb_init()
    return True

def internal_close_server():
    if _gta_proc is not None:
        uninstall_hook_quit_cmd()
        print('Closing debugger server...')
        os.kill(_gta_proc.pid, signal.SIGINT)

def start(args):
    """
        Start SoC & Core Initialization
    """
    if internal_start(args) is False:
        internal_close_server()
        return False
    return True
