using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.IO;
namespace Titano.Setup.Engine;
///
/// Record of one installation, kept as install-log.json in the install folder. The uninstaller carries no
/// payload, so everything it removes comes from here: payload files, shortcuts and file types. User data is never
/// listed.
///
internal sealed class InstallLog
{
public const string FileName = "install-log.json";
public int FormatVersion { get; set; } = 1;
public required string Product { get; set; }
public required string Version { get; set; }
public InstallScope Scope { get; set; }
public List Components { get; set; } = [];
/// Installed payload paths, relative to the install folder (the uninstaller and this log excluded).
public List Files { get; set; } = [];
///
/// Full paths of the shortcuts setup created, or would have created but found starting an existing program elsewhere
/// (another Titano product's copy, which hands them over to this one when it is uninstalled).
///
public List Shortcuts { get; set; } = [];
public List Associations { get; set; } = [];
[JsonIgnore]
public string ProductKey => SetupPaths.ProductKey(Product);
[JsonIgnore]
public string UninstallerName => SetupPaths.UninstallerName(Product);
/// The log in , or null when there is none or it is unreadable.
public static InstallLog? TryLoad(string directory)
{
var path = Path.Combine(directory, FileName);
try
{
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllBytes(path), InstallLogJson.Default.InstallLog) : null;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Titano.Core.Diagnostics.Log.Warning("setup", $"Install log '{path}' is unreadable", ex);
return null;
}
}
public void Save(string directory) =>
AtomicFile.WriteAllBytes(Path.Combine(directory, FileName), JsonSerializer.SerializeToUtf8Bytes(this, InstallLogJson.Default.InstallLog));
}
/// A file type registered by setup.
internal sealed record InstalledAssociation(string Extension, string ProgId);
[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)]
[JsonSerializable(typeof(InstallLog))]
internal sealed partial class InstallLogJson : JsonSerializerContext;