From b97a16d1759b785f237194581c5a0512f7a118be Mon Sep 17 00:00:00 2001
From: Niko Ehrenfeuchter <nikolaus.ehrenfeuchter@unibas.ch>
Date: Wed, 13 Dec 2017 10:39:25 +0100
Subject: [PATCH] Prevent shutdown if the service is busy.

Refers to #13
---
 AutoTx-Updater/Update-Service.ps1 | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

diff --git a/AutoTx-Updater/Update-Service.ps1 b/AutoTx-Updater/Update-Service.ps1
index 6bea491..33da4c6 100644
--- a/AutoTx-Updater/Update-Service.ps1
+++ b/AutoTx-Updater/Update-Service.ps1
@@ -46,6 +46,28 @@ function Ensure-ServiceRunning([string]$ServiceName) {
 }
 
 
+function ServiceIsBusy {
+    $StatusXml = "$($InstallationPath)\status.xml"
+    try {
+        [xml]$XML = Get-Content $StatusXml -ErrorAction Stop
+        if ($XML.ServiceStatus.TransferInProgress) {
+            Return $True
+        } else {
+            Write-Verbose "Service is idle, shutdown possible."
+            Return $False
+        }
+    }
+    catch {
+        $ex = $_.Exception.Message
+        $msg = "Trying to read the service status from [$($StatusXml)] failed! "
+        $msg += "The reported error message was:`n$($ex)"
+        Send-MailReport -Subject "Error parsing status of $($ServiceName)!" `
+            -Body $msg
+        Exit
+    }
+}
+
+
 function Exit-IfDirMissing([string]$DirName, [string]$Desc) {
     if (Test-Path -PathType Container $DirName) {
         Return
@@ -75,6 +97,12 @@ function Stop-MyService([string]$Message) {
         Log-Info "$($Message) (Service already in state 'Stopped')"
         Return
     }
+    if (ServiceIsBusy) {
+        $msg = "*DENYING* to stop the service $($ServiceName) as it is "
+        $msg += "currently busy.`nShutdown reason was '$($Message)'."
+        Log-Info $msg
+        Exit
+    }
     try {
         Log-Info "$($Message) Attempting service $($ServiceName) shutdown..."
         Stop-Service "$($ServiceName)" -ErrorAction Stop
-- 
GitLab