using Barcode.Host.Shared.Models.Stateless;
using CliWrap;
using CliWrap.Buffered;

namespace Barcode.Host.Server.Services;

public class LinuxGroupManager : ILinuxGroupManager
{

    public async Task<bool> IsInInputGroup()
    {
        BufferedCommandResult result = await Cli.Wrap("id")
            .ExecuteBufferedAsync();
        string output = result.StandardOutput;
        const StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
        bool inInputGroup = output.Split(new[] { ' ' }, options)
            .First(p => p.StartsWith("groups"))
            .Remove(0, "groups".Length)
            .Split(',', options)
            .Any(p => p.Contains("input"));
        return inInputGroup;
    }

    public async Task AddUserToInputGroup(string password)
    {
        using CancellationTokenSource cts = new();
        cts.CancelAfter(TimeSpan.FromSeconds(10));
        _ = await Cli.Wrap("bash")
            .WithArguments($"-c \"echo '{password}' | sudo -S gpasswd -a $USER input")
            .ExecuteBufferedAsync(cts.Token);
    }

    public async Task RebootSystem(string password)
    {
        using CancellationTokenSource cts = new();
        cts.CancelAfter(TimeSpan.FromSeconds(10));
        _ = await Cli.Wrap("bash")
            .WithArguments($"-c \"echo '{password}' | sudo -S reboot\"")
            .ExecuteBufferedAsync(cts.Token);
    }

}