--[[
  Copyright (c) 2023 by Plexim GmbH
  All rights reserved.

  A free license is granted to anyone to use this software for any legal
  non safety-critical purpose, including commercial applications, provided
  that:
  1) IT IS NOT USED TO DIRECTLY OR INDIRECTLY COMPETE WITH PLEXIM, and
  2) THIS COPYRIGHT NOTICE IS PRESERVED in its entirety.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
--]]

local U = require('common.utils')
local debug = require('debug')
local ExtTools = require('common.external_tools')

local function p_OnConnectFunction()
  if Target.Variables.EXTERNAL_MODE ~= 2 then
    -- only JTAG mode requires helper tool
    return {}
  end

  local m_osDir
  if Target.Variables.HOST_OS == 'win' then
    m_osDir = 'win'
  elseif Target.Variables.HOST_OS == 'mac' then
    m_osDir = 'osx'
  else
    U.error( -- FIX ME: Why not? Maybe we can and make this common code?
      'Host operating system (%s) does not support external mode over JTAG.' %
      {Target.Variables.HOST_OS})
  end

  -- Note directoryExists doesn't work when called from OnConnectFunction.lua
  -- These enforce functions are only able to verify a valid path is provided.
  -- Uniflash was used in the compile, so we don't do extensive checks here.
  local uniflashDir = ExtTools.enforceValidDirectoryExists({'uniflashDir', 'TI Uniflash'})

  local c2000BaseDir = 
     uniflashDir..'/deskdb/content/TICloudAgent/%s/ccs_base' % {m_osDir}

  -- C2Prog GDB server needed to connect via JTag
  local gdb_info = {
    opt_descriptor = 'C2Prog GDB server tools',
    opt_instructions = ExtTools.getNotFoundInstructions(),
  }
  local gdbServerDir = ExtTools.enforceValidDirectoryExists({'GdbServerDir', 'C2Prog GDB server tools'})
  if gdbServerDir == '' then
    U.error(
      'To connect via JTAG, please configure the %(opt_descriptor)s. %(opt_instructions)s' %
      gdb_info)
  else
    -- Checking for this version number file (build_info.txt) because we don't
    -- have a robust implementation of U.directoryExists that doesn't rely on
    -- Plecs:DirectoryExists().
    U.assertFileExists(gdbServerDir..'/build_info.txt', gdb_info)
  end

  -- determine c2p configuration settings
  local function targetDotLuaFilename(targetName)
    -- override deprecated targets here
    return (Target.Name == 'TI2837xS') and 'TI2837x' or targetName
  end

  local T = require('targets.'..targetDotLuaFilename(Target.Name))
  local board = T.getBoardNameFromComboIndex(Target.Variables.board)

  local c2pConfig
  if board ~= 'custom' then
    c2pConfig = T.getOptions().c2pConfigs[board]
    if c2pConfig == nil then
      U.error('This board is not supported for external mode communication over JTAG.')
    end
  else
    c2pConfig = T.getC2pConfigFromCcxml(Target.Variables.uniflashFile)
  end

  local gdbServerExe = gdbServerDir..'/c2p-gdb-server'

  local gdbServerCmd = ''
     ..U.shellQuote(gdbServerExe)
     ..' --ccs-base-path '..U.shellQuote(c2000BaseDir)
     ..' --server-port=%(gdbPort)d --non-intrusive --single %(c2pConfig)s' %
     {
       gdbPort = ExtTools.getGDBPort(),
       c2pConfig = c2pConfig,
     }

  return {
    ConnectionHelper = {
      Command = gdbServerCmd,
      DelayBeforeConnectMs = 1000,
      DelayAfterDisconnectMs = 1000,
      WaitForFinishedMs = 500,
      TcpPort = nil,
    },
  }
end

local ok, res = xpcall(p_OnConnectFunction, debug.traceback)

if ok then
  U.dumpLog()
  return res
else  -- there was an error, res will be an error including the stack trace
  return U.stripTraceOrRethrowError(res)
end
