using System;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;

namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Host.Ipc;

/// <summary>
///     Builds the <see cref="PipeSecurity"/> required by <c>driver-stability.md §"IPC Security"</c>:
///     only the configured OtOpcUa server principal SID gets <c>ReadWrite | Synchronize</c>;
///     LocalSystem and Administrators are explicitly denied. Any other authenticated user falls
///     through to the implicit deny.
/// </summary>
public static class PipeAcl
{
    public static PipeSecurity Create(SecurityIdentifier allowedSid)
    {
        if (allowedSid is null) throw new ArgumentNullException(nameof(allowedSid));

        var security = new PipeSecurity();

        security.AddAccessRule(new PipeAccessRule(
            allowedSid,
            PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize,
            AccessControlType.Allow));

        var localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
        var admins      = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

        if (allowedSid != localSystem)
            security.AddAccessRule(new PipeAccessRule(localSystem, PipeAccessRights.FullControl, AccessControlType.Deny));
        if (allowedSid != admins)
            security.AddAccessRule(new PipeAccessRule(admins,      PipeAccessRights.FullControl, AccessControlType.Deny));

        // Owner = allowed SID so the deny rules can't be removed without write-DACL rights.
        security.SetOwner(allowedSid);

        return security;
    }
}
