@echo off
setlocal disableDelayedExpansion

:Variables
set InputFile=%2
set OutputFile=%InputFile%#
set entity=%1
set "_strFind=ConfigureRepositoryWrapper(this IServiceCollection services)"
set "_strInsert1=            services.AddScoped(typeof(IBaseRepository<%entity%>), typeof(%entity%Repository));"
set doreplace=0

rem if already inserted, do nothing
:Check
for /F "delims=" %%L in ('findstr /n "^" "%InputFile%"') do (
  set "line=%%L"
  setlocal EnableDelayedExpansion

  set "line=!line:*:=!"
  if "!line!" neq "" (
    set "_line=!line:%_strInsert1%=!"
  ) else (
    set _line=!line!
  )
  if "!_line!" neq "!line!" goto finish
  endlocal
)

:Replace
>"%OutputFile%" (
  for /F "delims=" %%L in ('findstr /n "^" "%InputFile%"') do (
    set "line=%%L"
    setlocal EnableDelayedExpansion

    set "line=!line:*:=!"
    if "!line!" neq "" (
      set "_line=!line:%_strFind%=!"
    ) else (
      set _line=!line!
    )


    if "!_line!" neq "!line!" (
           echo.!line!
           endlocal
           set doreplace=1
    ) else (
           echo.!line!
           if !doreplace!==1 (
             echo !_strInsert1!
           )
       endlocal
       set doreplace=0
    )
  )
)

del %InputFile%
copy %OutputFile% %InputFile%>nul
del %OutputFile%

:finish