#Command in powershell window: ./mission.ps1 E:\temp\*.miz A-10C A-10C_2    it will change all A-10C aircraft to A-10C_2 in all missions in the folder E:\temp\
#all miz files in 1 folder or specific miz file name
#E:\temp\*.miz  or E:\temp\mymission_file.miz (if the script is in the same folder with all miz file just enter *.miz or mymission_file.miz skipping full path
$MIZ=$args[0]

#Aircraft type in original mission
#$ORIG_AIRCRAFT=$args[1]
#Aircraft type in new mission
$NEW_AIRCRAFT=$args[1]

#apply to all miz file or specific one
Get-ChildItem $MIZ | ForEach-Object {

  $_



# Load miz file 
try { $null = [IO.Compression.ZipFile] }
catch { [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') }

# Open miz file 
try { $fileZip = [System.IO.Compression.ZipFile]::Open( $_, 'Update' ) }
catch { throw "Another process has locked the '$_' file." }

# Find the mission file within the zip file

$fileZip.Entries | Where-Object { $_.FullName -EQ 'mission' }


#read the contents mission file to $text 
$desiredFile = [System.IO.StreamReader]($fileZip.Entries | Where-Object { $_.FullName -EQ 'mission' }).Open()
$text = $desiredFile.ReadToEnd()
$desiredFile.Close()
$desiredFile.Dispose()

# replace aircraft type in $text
#$text | Select-String '["type"] = "A-10C",' -SimpleMatch
#$text | Select-String -Include '"A-10C_2"'
#$text | Out-String -Stream | Select-String '["type"] = "A-10C_2",' -SimpleMatch -Quiet 
$text | Out-String -Stream | Select-String $NEW_AIRCRAFT -SimpleMatch -Quiet 




#$text | Select-String $([Regex]::Escape('`["type"]` =` "A-10C",'))
#$text = $text -replace $ORIG_AIRCRAFT, $NEW_AIRCRAFT

# Re-open the file this time with streamwriter
$desiredFile = [System.IO.StreamWriter]($fileZip.Entries | Where-Object { $_.FullName -EQ 'mission' }).Open()
$desiredFile.BaseStream.SetLength(0)

# Insert the $text to the mission file and close
$desiredFile.Write($text -join "`r`n")
$desiredFile.Flush()
$desiredFile.Close()

# Write the changes and close the zip file
$fileZip.Dispose()

}
