###############################################
# KONFIGURACJA
###############################################

# Nazwa użytkownika do sprawdzenia
$UserName = "user01"
$Domain   = "DOMAIN"

# Czy analizować podfoldery
$Recurse = $true
$Depth   = 5

# Ścieżka raportu HTML
$OutputPath = ".\UserdataAudit_$UserName.html"

###############################################
# LOGIKA SKRYPTU
###############################################

$UserSam = "$Domain\$UserName"

Write-Host "Analiza użytkownika: $UserSam" -ForegroundColor Cyan

# 1. Znajdź zmapowany dysk do \\server\userdata
$mappedDrive = Get-WmiObject Win32_LogicalDisk |
    Where-Object { $_.ProviderName -match "\\\\server\\userdata" }

if (-not $mappedDrive) {
    Write-Host "Nie znaleziono zmapowanego dysku do \\server\userdata" -ForegroundColor Red
    exit
}

$DriveLetter = $mappedDrive.DeviceID
$UserFolderPath = Join-Path $DriveLetter $UserName

if (-not (Test-Path $UserFolderPath)) {
    Write-Host "Folder użytkownika nie istnieje: $UserFolderPath" -ForegroundColor Red
    exit
}

# Funkcja analizy jednego folderu
function Analyze-Folder {
    param(
        [string]$Path,
        [string]$UserSam
    )

    $acl = Get-Acl -Path $Path
    $owner = $acl.Owner

    # ACE NTFS
    $ntfsAll = $acl.Access

    # ACE użytkownika
    $ntfsUser = $acl.Access | Where-Object {
        $_.IdentityReference -match [regex]::Escape($UserSam)
    }

    # Effective Access (na podstawie grup)
    $groups = (New-Object System.Security.Principal.NTAccount($UserSam)).Translate([System.Security.Principal.SecurityIdentifier]).Groups |
        ForEach-Object { $_.Translate([System.Security.Principal.NTAccount]).Value }

    $effective = $acl.Access | Where-Object {
        $groups -contains $_.IdentityReference.Value -or $_.IdentityReference.Value -eq $UserSam
    }

    # Dziedziczenie
    $hasInheritance = -not $acl.AreAccessRulesProtected

    # Nadmiarowe ACE
    $allowed = @(
        $UserSam,
        "NT AUTHORITY\SYSTEM",
        "BUILTIN\Administrators"
    )

    $extraAces = $acl.Access | Where-Object {
        $allowed -notcontains $_.IdentityReference.Value
    }

    # Share permissions
    $sharePerms = Get-SmbShareAccess -Name "userdata" -ErrorAction SilentlyContinue

    return [PSCustomObject]@{
        Path           = $Path
        User           = $UserSam
        Owner          = $owner
        HasInheritance = $hasInheritance
        ExtraAces      = $extraAces
        Effective      = $effective
        SharePerms     = $sharePerms
    }
}

# Zbierz foldery do analizy
$folders = @($UserFolderPath)

if ($Recurse) {
    $folders += Get-ChildItem -Path $UserFolderPath -Directory -Recurse -Depth $Depth | Select-Object -ExpandProperty FullName
}

$results = foreach ($folder in $folders) {
    Analyze-Folder -Path $folder -UserSam $UserSam
}

# Generowanie raportu HTML
$rows = foreach ($item in $results) {

    $status = "OK"
    $color  = "green"
    $issues = @()

    # Właściciel
    $expectedOwner1 = $item.User
    $expectedOwner2 = "BUILTIN\Administrators"

    if ($item.Owner -ne $expectedOwner1 -and $item.Owner -ne $expectedOwner2) {
        $status = "BŁĘDNY WŁAŚCICIEL"
        $color  = "red"
        $issues += "Nieprawidłowy właściciel: $($item.Owner)"
    }

    # Dziedziczenie
    if (-not $item.HasInheritance) {
        if ($status -eq "OK") {
            $status = "BRAK DZIEDZICZENIA"
            $color  = "orange"
        }
        $issues += "Dziedziczenie ACL wyłączone"
    }

    # Nadmiarowe ACE
    if ($item.ExtraAces.Count -gt 0) {
        if ($status -eq "OK") {
            $status = "NADMIAROWE ACE"
            $color  = "orange"
        }
        $issues += "Nadmiarowe ACE: " + ($item.ExtraAces.IdentityReference -join ", ")
    }

    $issuesText = if ($issues.Count -gt 0) { $issues -join " | " } else { "" }

    [PSCustomObject]@{
        Path   = $item.Path
        User   = $item.User
        Owner  = $item.Owner
        Status = $status
        Issues = $issuesText
        Color  = $color
    }
}

# HTML
$htmlRows = $rows | ForEach-Object {
    "
        $($_.Path)
        $($_.User)
        $($_.Owner)
        $($_.Status)
        $($_.Issues)
    "
} | Out-String

$html = @"


    
    Audyt userdata
    


    

Audyt uprawnień userdata – $UserSam

Data: $(Get-Date)

$htmlRows
Ścieżka Użytkownik Właściciel Status Uwagi
"@ $html | Out-File -FilePath $OutputPath -Encoding UTF8 Write-Host "Raport zapisany do: $OutputPath" -ForegroundColor Green