summaryrefslogtreecommitdiffstats
path: root/src/main.lib/Services/Legacy/LegacyTaskSchedulerService.cs
blob: e761339534a8d9a75c79fda6b9f3a7346629b20b (plain)
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
using Microsoft.Win32.TaskScheduler;
using PKISharp.WACS.Configuration;
using PKISharp.WACS.Host.Services.Legacy;
using System.IO;
using System.Linq;

namespace PKISharp.WACS.Services.Legacy
{
    internal class LegacyTaskSchedulerService
    {
        private readonly MainArguments _options;
        private readonly ISettingsService _settings;
        private readonly ILogService _log;

        public LegacyTaskSchedulerService(LegacySettingsService settings, MainArguments main, ILogService log)
        {
            _options = main;
            _settings = settings;
            _log = log;
        }

        public void StopTaskScheduler()
        {
            using var taskService = new TaskService();
            var taskName = "";
            Task existingTask = null;
            foreach (var clientName in _settings.Client.ClientName.AsEnumerable().Reverse())
            {
                taskName = $"{clientName} {CleanFileName(_options.ImportBaseUri)}";
                existingTask = taskService.GetTask(taskName);
                if (existingTask != null)
                {
                    break;
                }
            }

            if (existingTask != null)
            {
                existingTask.Definition.Settings.Enabled = false;
                _log.Warning("Disable existing task {taskName} in Windows Task Scheduler to prevent duplicate renewals", taskName);
                taskService.RootFolder.RegisterTaskDefinition(taskName, existingTask.Definition, TaskCreation.CreateOrUpdate, null);
            }
        }

        public string CleanFileName(string fileName) => Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
    }
}