; searchreplace.pb
; ------------------------------------------------------------
; search a string in a file and replace all occurences
; LICENSE  : GPL
; AUTHOR   : Michael H.G. Schmidt
; EMAIL    : michael@schmidt2.de
; DATE     : 20230223
; ------------------------------------------------------------
;

OpenConsole()

Procedure Usage()
	ConsoleColor(14,0)
	PrintN("")
	PrintN("usage: searchreplace <filename> <oldstring> <newstring> [/S]")
	PrintN("")
	ConsoleColor(15,0)
	PrintN("search a string in a file and replace all occurences")
	PrintN("  oldstring: string to search (RegEx aware)")
	PrintN("  newstring: string to replace")
	PrintN("         /S: silent/hide output (use this for passwords!)")
	ConsoleColor(7,0)
	PrintN("")
	End 1
EndProcedure

; check commandline ...
If ( CountProgramParameters() < 3 Or CountProgramParameters() > 4 )
  Usage()
EndIf

; vars
tempfile$ = workfile$ + "_T"
silent=0

; get arguments ...
workfile$  = ProgramParameter(0)
oldstring$ = ProgramParameter(1)
newstring$ = ProgramParameter(2)

; hide output
If ( CountProgramParameters() = 4 )
  If (UCase(ProgramParameter(3)) = "/S" )
    silent=1
  Else
    Usage()
  EndIf
EndIf

;
; MAIN
;

; open workfile ...
If Not ReadFile(0, workfile$, #PB_File_SharedRead | #PB_File_NoBuffering)
  PrintN("ERROR while opening file [ " + workfile$ + " ] for reading!")
  End 99
EndIf

; cleanup ...
DeleteFile(tempfile$,#PB_FileSystem_Force)

; open tempfile ...
If Not OpenFile(1, tempfile$, #PB_File_SharedWrite | #PB_File_NoBuffering)
  PrintN("ERROR while opening tempfile [ " + tempfile$ + " ] for writing!")
  End 99
EndIf

If ( silent = 1 )
  PrintN("working on [ "+ workfile$ +" ] and replacing string [ "+ oldstring$ +" ] With [ ******** ] ...")
Else
  PrintN("working on [ "+ workfile$ +" ] and replacing string [ "+ oldstring$ +" ] With [ "+ newstring$ +" ] ...")
EndIf

Repeat
  ; read a line ...
  line$ = ReadString(0)
  
  ; search and replace ...
  If ( CreateRegularExpression(0,oldstring$,#PB_RegularExpression_NoCase|#PB_RegularExpression_AnyNewLine) )
    result$=ReplaceRegularExpression(0,line$,newstring$)
  Else
    PrintN("ERROR: regular expression not valid!")
    End 1
  EndIf
  
  ; write to tempfile ...
  WriteStringN(1, result$)  
Until Eof(0)

; close files ...
CloseFile(0)
CloseFile(1)

; delete workfile ...
DeleteFile(workfile$,#PB_FileSystem_Force)

; move tempfile in place of original file ...
dummy = RenameFile(tempfile$, workfile$)

End 0

; IDE Options = PureBasic 5.73 LTS (Windows - x64)
; CursorPosition = 26
; Folding = -
; EnableXP