param (
    [string]$projectRoot
    [string]$projectName
)

# 自动获取 OpenOCD 的路径
$openOcdPath = (Get-Command openocd).Source
if (-not $openOcdPath) {
    Write-Host "未找到 OpenOCD，请确保已正确安装并在 PATH 中。"
    exit 1
}

# 获取 OpenOCD 的目录并构建 scriptsPath
$openOcdDir = Split-Path (Split-Path $openOcdPath)
$scriptsPath = Join-Path $openOcdDir "share/openocd/scripts"

# 定义文件路径
$mapFilePath = Join-Path $projectRoot "cmake-build-debug/$projectName.map"
$rttCfgPath = Join-Path $projectRoot "rtt.cfg"

# 读取 .map 文件内容
$content = Get-Content $mapFilePath

# 使用 Select-String 提取地址
$match = $content | Select-String -Pattern '^\s*0x([0-9a-fA-F]+)\s+.*_SEGGER_RTT'

# 获取地址
if ($match) {
    $address = $match.Matches.Groups[1].Value
    $newRttLine = "rtt setup 0x$address 1024 ""SEGGER RTT"""

    # 读取 rtt.cfg 内容
    $rttContent = Get-Content $rttCfgPath

    # 查找并替换旧的 rtt setup 行
    $updatedContent = $rttContent -replace 'rtt setup 0x[0-9a-fA-F]+ 1024 "SEGGER RTT"', $newRttLine

    # 将更新后的内容写回文件
    Set-Content $rttCfgPath $updatedContent

    Write-Host "已更新 rtt.cfg 中的 RTT 地址为: 0x$address"

    # 启动 OpenOCD
    Start-Process -FilePath $openOcdPath -ArgumentList "-s $scriptsPath -f $rttCfgPath" -WorkingDirectory $projectRoot
} else {
    Write-Host "未找到 SEGGER RTT 地址，未进行更新"
}
