using System.IO;
using System.Runtime.InteropServices;
using Titano.Core.Diagnostics;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Interop;
namespace Titano.Setup.Engine;
/// An installation found on disk: its folder and log.
internal sealed record InstalledProduct(string Directory, InstallLog Log);
///
/// Removes an installation using only its log: shortcuts that still start its programs (handed to another Titano
/// product that installed the same program and shares them), file types, logged files, the log, the Add/Remove
/// Programs entry and the sign-in entries of its programs, then the uninstaller itself. Files the log does not list,
/// and anything that starts a program it does not list, are left alone; user data is deleted only through a plan the
/// user saw and chose in the window. The Windows services of its programs are stopped and deleted by the caller first
/// (), as that may need an elevated step.
///
internal static class UninstallEngine
{
/// The installation to remove: /DIR, the uninstaller's own folder, or the registered location.
public static InstalledProduct? Locate(string? directory, string? productFromPayload)
{
var candidates = new List { directory, Path.GetDirectoryName(Environment.ProcessPath) };
if (productFromPayload is not null) candidates.Add(SetupRegistry.FindInstall(SetupPaths.ProductKey(productFromPayload))?.Directory);
foreach (var candidate in candidates)
{
if (string.IsNullOrEmpty(candidate)) continue;
if (InstallLog.TryLoad(candidate) is { } log) return new InstalledProduct(Path.GetFullPath(candidate), log);
}
return null;
}
/// The "Remove my data" plan the user confirmed; null keeps the user data.
public static void Uninstall(InstalledProduct product, UserDataPlan? userData, IProgress? progress)
{
var (directory, log) = product;
Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {userData is not null})");
// First, so that a failure here leaves the program installed and the uninstaller able to retry.
if (userData is { Entries.Count: > 0 })
{
Log.Info("setup", $"Removing {userData.Entries.Count} entries of '{userData.Folder}' at the user's request");
userData.Remove();
}
if (log.Shortcuts.Count > 0)
{
var others = SetupRegistry.OtherInstalls(directory, InstallEngine.Publisher);
foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope, directory, others);
}
progress?.Report(new SetupProgress(0.1, string.Empty));
var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList();
foreach (var a in fileTypes) SetupRegistry.UnregisterFileType(log.Scope, a.Extension, a.ProgId);
if (fileTypes.Count > 0) NativeMethods.NotifyAssociationsChanged();
progress?.Report(new SetupProgress(0.2, string.Empty));
var failed = InstalledFiles.Remove(directory, log.Files.Where(PayloadPath.IsValid));
progress?.Report(new SetupProgress(0.8, string.Empty));
if (failed.Count > 0)
{
// Keep the entry and a log of what is left, so the user can run the uninstaller again.
log.Files = [.. failed];
log.Shortcuts = [];
log.Associations = [];
log.Save(directory);
throw new SetupException(SetupExitCode.Failed, $"{failed.Count} file(s) could not be removed.");
}
SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey);
try
{
SetupRegistry.DeleteStartupEntries(CommandProgram.FullPaths(directory, log.Files));
}
catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException)
{
// Windows skips a sign-in entry whose program is gone; not worth failing the removal.
Log.Warning("setup", "Sign-in entries not removed", ex);
}
File.Delete(Path.Combine(directory, InstallLog.FileName));
var uninstaller = Path.Combine(directory, log.UninstallerName);
try
{
if (Environment.ProcessPath is { } self && Path.GetFullPath(self).Equals(Path.GetFullPath(uninstaller), StringComparison.OrdinalIgnoreCase))
{
SelfCleanup.Schedule(uninstaller);
}
else
{
if (File.Exists(uninstaller)) File.Delete(uninstaller);
InstalledFiles.Remove(directory, [], removeEmptyRoot: true);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception)
{
// Everything else is gone; a leftover uninstaller is not worth failing the removal.
Log.Warning("setup", $"Uninstaller '{uninstaller}' not removed", ex);
}
progress?.Report(new SetupProgress(1, string.Empty));
}
///
/// Deletes a shortcut recorded in a log, but only a .lnk directly in the Start menu or desktop folder that
/// still starts a program inside : another product installing a program of the same
/// name may have pointed it at its own copy since. When another installation () shares
/// the shortcut and has the same program, the shortcut is pointed at that copy instead, so the program that stays
/// installed keeps its shortcut.
///
public static void DeleteShortcut(string link, InstallScope scope, string directory, IReadOnlyList others)
{
var folder = Path.GetDirectoryName(link);
var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase)
&& (folder.Equals(SetupPaths.StartMenu(scope), StringComparison.OrdinalIgnoreCase)
|| folder.Equals(SetupPaths.Desktop(scope), StringComparison.OrdinalIgnoreCase));
if (!allowed)
{
Log.Warning("setup", $"Ignoring shortcut outside the shortcut folders: '{link}'");
return;
}
try
{
if (ShellLink.TargetOf(link) is not { } target) return;
if (!CommandProgram.IsPathInside(target, directory))
{
Log.Info("setup", $"Shortcut '{link}' now starts '{target}'; kept");
return;
}
if (SharedCopy(link, scope, directory, target, others) is { } copy)
{
ShellLink.Create(link, copy, Path.GetFileNameWithoutExtension(link));
Log.Info("setup", $"Shortcut '{link}' now starts '{copy}', which stays installed");
return;
}
File.Delete(link);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or COMException)
{
Log.Warning("setup", $"Shortcut '{link}' not removed", ex);
}
}
///
/// The same program as (the same path inside its folder) installed by another product of
/// the same scope whose log lists too; null when there is none.
///
private static string? SharedCopy(string link, InstallScope scope, string directory, string target, IReadOnlyList others)
{
string relative;
try
{
relative = PayloadPath.FromRelative(Path.GetRelativePath(directory, target));
}
catch (Exception ex) when (ex is PayloadException or ArgumentException)
{
return null;
}
foreach (var other in others)
{
if (other is not { Directory: { } otherDirectory, Log: { } log } || log.Scope != scope) continue;
if (!log.Shortcuts.Contains(link, StringComparer.OrdinalIgnoreCase) || !log.Files.Contains(relative, PayloadPath.Comparer)) continue;
// The folder comes from another product's registry entry: one Windows cannot use is skipped.
if (!SetupPaths.IsUsableInstallDirectory(otherDirectory)) continue;
var copy = PayloadPath.Resolve(otherDirectory, relative);
if (File.Exists(copy)) return copy;
}
return null;
}
}