forked from Nonary/ResolutionAutomation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelpers.ps1
More file actions
293 lines (232 loc) · 9.72 KB
/
Helpers.ps1
File metadata and controls
293 lines (232 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
param(
[Parameter(Position = 0, Mandatory = $true)]
[Alias("n")]
[string]$scriptName,
[Alias("t")]
[Parameter(Position = 1, Mandatory = $false)]
[int]$terminate
)
$path = (Split-Path $MyInvocation.MyCommand.Path -Parent)
Set-Location $path
$script:attempt = 0
function OnStreamEndAsJob() {
return Start-Job -Name "$scriptName-OnStreamEnd" -ScriptBlock {
param($path, $scriptName, $arguments)
function Write-Debug($message){
if ($arguments['debug']) {
Write-Host "DEBUG: $message"
}
}
Write-Host $arguments
Write-Debug "Setting location to $path"
Set-Location $path
Write-Debug "Loading Helpers.ps1 with script name $scriptName"
. .\Helpers.ps1 -n $scriptName
Write-Debug "Loading Events.ps1 with script name $scriptName"
. .\Events.ps1 -n $scriptName
Write-Host "Stream has ended, now invoking code"
Write-Debug "Creating pipe with name $scriptName-OnStreamEnd"
$job = Create-Pipe -pipeName "$scriptName-OnStreamEnd"
while ($true) {
$maxTries = 25
$tries = 0
Write-Debug "Checking job state: $($job.State)"
if ($job.State -eq "Completed") {
Write-Host "Another instance of $scriptName has been started again. This current session is now redundant and will terminate without further action."
Write-Debug "Job state is 'Completed'. Exiting loop."
break;
}
Write-Debug "Invoking OnStreamEnd with arguments: $arguments"
if ((OnStreamEnd $arguments)) {
Write-Debug "OnStreamEnd returned true. Exiting loop."
break;
}
if ((IsCurrentlyStreaming)) {
Write-Host "Streaming is active. To prevent potential conflicts, this script will now terminate prematurely."
}
while (($tries -lt $maxTries) -and ($job.State -ne "Completed")) {
Start-Sleep -Milliseconds 200
$tries++
}
}
Write-Debug "Sending 'Terminate' message to pipe $scriptName-OnStreamEnd"
Send-PipeMessage "$scriptName-OnStreamEnd" Terminate
} -ArgumentList $path, $scriptName, $script:arguments
}
function IsCurrentlyStreaming() {
$sunshineProcess = Get-Process sunshine -ErrorAction SilentlyContinue
if ($null -eq $sunshineProcess) {
return $false
}
return $null -ne (Get-NetUDPEndpoint -OwningProcess $sunshineProcess.Id -ErrorAction Ignore)
}
function Stop-Script() {
Send-PipeMessage -pipeName $scriptName Terminate
}
function Send-PipeMessage($pipeName, $message) {
Write-Debug "Attempting to send message to pipe: $pipeName"
$pipeExists = Get-ChildItem -Path "\\.\pipe\" | Where-Object { $_.Name -eq $pipeName }
Write-Debug "Pipe exists check: $($pipeExists.Length -gt 0)"
if ($pipeExists.Length -gt 0) {
$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", $pipeName, [System.IO.Pipes.PipeDirection]::Out)
Write-Debug "Connecting to pipe: $pipeName"
$pipe.Connect(3000)
$streamWriter = New-Object System.IO.StreamWriter($pipe)
Write-Debug "Sending message: $message"
$streamWriter.WriteLine($message)
try {
$streamWriter.Flush()
$streamWriter.Dispose()
$pipe.Dispose()
Write-Debug "Message sent and resources disposed successfully."
}
catch {
Write-Debug "Error during disposal: $_"
# We don't care if the disposal fails, this is common with async pipes.
# Also, this powershell script will terminate anyway.
}
}
else {
Write-Debug "Pipe not found: $pipeName"
}
}
function Create-Pipe($pipeName) {
return Start-Job -Name "$pipeName-PipeJob" -ScriptBlock {
param($pipeName, $scriptName)
Register-EngineEvent -SourceIdentifier $scriptName -Forward
$pipe = New-Object System.IO.Pipes.NamedPipeServerStream($pipeName, [System.IO.Pipes.PipeDirection]::In, 10, [System.IO.Pipes.PipeTransmissionMode]::Byte, [System.IO.Pipes.PipeOptions]::Asynchronous)
$streamReader = New-Object System.IO.StreamReader($pipe)
Write-Host "Waiting for named pipe to recieve kill command"
$pipe.WaitForConnection()
$message = $streamReader.ReadLine()
if ($message) {
Write-Host "Terminating pipe..."
$pipe.Dispose()
$streamReader.Dispose()
New-Event -SourceIdentifier $scriptName -MessageData $message
}
} -ArgumentList $pipeName, $scriptName
}
function Remove-OldLogs {
# Get all log files in the directory
$logFiles = Get-ChildItem -Path './logs' -Filter "log_*.txt" -ErrorAction SilentlyContinue
# Sort the files by creation time, oldest first
$sortedFiles = $logFiles | Sort-Object -Property CreationTime -ErrorAction SilentlyContinue
if ($sortedFiles) {
# Calculate how many files to delete
$filesToDelete = $sortedFiles.Count - 10
# Check if there are more than 10 files
if ($filesToDelete -gt 0) {
# Delete the oldest files, keeping the latest 10
$sortedFiles[0..($filesToDelete - 1)] | Remove-Item -Force
}
}
}
function Start-Logging {
# Get the current timestamp
$timeStamp = [int][double]::Parse((Get-Date -UFormat "%s"))
$logDirectory = "./logs"
# Define the path and filename for the log file
$logFileName = "log_$timeStamp.txt"
$logFilePath = Join-Path $logDirectory $logFileName
# Check if the log directory exists, and create it if it does not
if (-not (Test-Path $logDirectory)) {
New-Item -Path $logDirectory -ItemType Directory
}
# Start logging to the log file
Start-Transcript -Path $logFilePath
}
function Stop-Logging {
Stop-Transcript
}
function Get-Settings {
# Read the file content
$jsonContent = Get-Content -Path ".\settings.json" -Raw
# Remove single line comments
$jsonContent = $jsonContent -replace '//.*', ''
# Remove multi-line comments
$jsonContent = $jsonContent -replace '/\*[\s\S]*?\*/', ''
# Remove trailing commas from arrays and objects
$jsonContent = $jsonContent -replace ',\s*([\]}])', '$1'
try {
# Convert JSON content to PowerShell object
$jsonObject = $jsonContent | ConvertFrom-Json
return $jsonObject
}
catch {
Write-Error "Failed to parse JSON: $_"
}
}
function Update-JsonProperty {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$FilePath,
[Parameter(Mandatory = $true)]
[string]$Property,
[Parameter(Mandatory = $true)]
[object]$NewValue
)
# Read the file as a single string.
$content = Get-Content -Path $FilePath -Raw
# Remove comments (both // and /* */ style) and trailing commas
$strippedContent = $content -replace '//.*?(\r?\n|$)', '$1' # Remove single line comments
$strippedContent = $strippedContent -replace '/\*[\s\S]*?\*/', '' # Remove multi-line comments
$strippedContent = $strippedContent -replace ',(\s*[\]}])', '$1' # Remove trailing commas
# Format the new value properly
if ($NewValue -is [string]) {
# Convert the string to a JSON-compliant string.
$formattedValue = (ConvertTo-Json $NewValue -Compress)
} else {
$formattedValue = $NewValue.ToString().ToLower()
}
# Build a regex pattern for matching the property.
$escapedProperty = [regex]::Escape($Property)
$pattern = '"' + $escapedProperty + '"\s*:\s*[^,}\r\n]+'
# Check if the property exists in the stripped content
if ($strippedContent -match $pattern) {
# Property exists, just update its value in the original content
$replacement = '"' + $Property + '": ' + $formattedValue
$updatedContent = [regex]::Replace($content, $pattern, $replacement)
} else {
# Property doesn't exist, need to add it
# Find the last property in the JSON object
$lastPropPattern = ',?\s*"([^"]+)"\s*:\s*[^,}\r\n]+'
if ($content -match '}\s*$') {
# Find the last occurrence of a property
$lastMatch = [regex]::Matches($content, $lastPropPattern)[-1]
$lastPropIndex = $lastMatch.Index + $lastMatch.Length
# Check if the last property ends with a comma
$endsWithComma = $content.Substring($lastPropIndex).TrimStart() -match '^\s*,'
# Prepare the new property string
$newPropString = ""
if (!$endsWithComma) {
$newPropString += ","
}
$newPropString += "`n `"$Property`": $formattedValue"
# Insert the new property before the closing brace
$closingBraceIndex = $content.LastIndexOf('}')
$updatedContent = $content.Substring(0, $closingBraceIndex).TrimEnd() +
$newPropString +
"`n}" +
$content.Substring($closingBraceIndex + 1)
} else {
Write-Error "Unable to find a proper location to insert the new property. JSON file may be malformed."
return
}
}
# Write the updated content back.
Set-Content -Path $FilePath -Value $updatedContent
}
function Wait-ForStreamEndJobToComplete() {
$job = OnStreamEndAsJob
while ($job.State -ne "Completed") {
$job | Receive-Job
Start-Sleep -Seconds 1
}
$job | Wait-Job | Receive-Job
}
if ($terminate -eq 1) {
Write-Host "Stopping Script"
Stop-Script | Out-Null
}