param(
    [Parameter(Mandatory = $true)][string]$user,
    [switch]$Force,
    [switch]$Version
)

# -----------------------------------------
# Run once guard
# -----------------------------------------
$Vendor = "Shinken"
$ScriptName = "WinRMSDDLConfig"
$RegPath = "HKLM:\SOFTWARE\$Vendor\$ScriptName"
$FlagName = "Completed"
$SCRIPT_VERSION = "V02.00.00-RC000.11"

if ($Version) {
    Write-Host "Version : $SCRIPT_VERSION" -ForegroundColor Gray
    exit 0
}

if (-not $Force) {
    if (Test-Path "$RegPath") {
        $Flag = (Get-ItemProperty -Path $RegPath -Name $FlagName -ErrorAction SilentlyContinue).$FlagName
        if ($Flag -eq 1) {
            Write-Host "Script has already run once. Aborting.."
            Write-Host "Use -Force to run it anyway."
            exit 0
        }
    }
}

if (-not (Test-Path $RegPath)) { New-Item -Path $RegPath -Force | Out-Null }
New-ItemProperty -Path $RegPath -Name $FlagName -Value 1 -PropertyType DWord -Force | Out-Null

# -----------------------------------------
# The scripts starts here
# -----------------------------------------

$GENERIC_READ = 0x80000000
$GENERIC_EXECUTE = 0x20000000
 
$user_sid = (New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList $user).Translate([System.Security.Principal.SecurityIdentifier])
 
# get the existing SDDL of the WinRM listener
$sddl = (Get-Item -Path WSMan:\localhost\Service\RootSDDL).Value
 
# convert the SDDL string to a SecurityDescriptor object
$sd = New-Object -TypeName System.Security.AccessControl.CommonSecurityDescriptor -ArgumentList $false, $false, $sddl
 
# apply a new DACL to the SecurityDescriptor object
$sd.DiscretionaryAcl.AddAccess(
    [System.Security.AccessControl.AccessControlType]::Allow,
    $user_sid,
    ($GENERIC_READ -bor $GENERIC_EXECUTE),
    [System.Security.AccessControl.InheritanceFlags]::None,
    [System.Security.AccessControl.PropagationFlags]::None
)
 
# get the SDDL string from the changed SecurityDescriptor object
$new_sddl = $sd.GetSddlForm([System.Security.AccessControl.AccessControlSections]::All)
 
# apply the new SDDL to the WinRM listener
Set-Item -Path WSMan:\localhost\Service\RootSDDL -Value $new_sddl -Force
Write-Host "Permissions de 'Lecture' et 'Execution' WinRM ajoutées pour l'utilisateur ou groupe $user" -ForegroundColor Green
