[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

if (Get-PackageProvider -ListAvailable -Name NuGet -ErrorAction SilentlyContinue) {
    Write-Host "NuGet Already Installed"
} 
else {
    try {
        Install-PackageProvider -Name NuGet -Confirm:$False -Force  
    }
    catch [Exception] {
        $_.message 
        exit
    }
}

if (Get-Module -ListAvailable -Name AzureADPreview) {
    Write-Host "AzureADPreview Already Installed"
} 
else {
    try {
        Install-Module -Name AzureADPreview -AllowClobber -Confirm:$False -Force  
    }
    catch [Exception] {
        $_.message 
        exit
    }
}

if (Get-InstalledModule -Name Az -ErrorAction SilentlyContinue) {
    Write-Host "Az Already Installed"
} 
else {
    try {
        Install-Module -Name Az -AllowClobber -Confirm:$False -Force
    }
    catch [Exception] {
        $_.message 
        exit
    }
}
<#
$appName = 'AZCmdlets'
$drive = 'C:\Temp'
New-Item -Path $drive -Name $appName  -ItemType Directory -ErrorAction SilentlyContinue
$LocalPath = $drive + '\' + $appName 
set-Location $LocalPath
$SetupURL = 'https://github.com/Azure/azure-powershell/releases/download/v6.3.0-August2021/Az-Cmdlets-6.3.0.34604-x64.msi'
$setupmsi = 'AzCmdlets.msi'
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $SetupURL -OutFile $setupmsi

Set-Location -Path C:\Temp\AzCmdlets\
Start-Process -FilePath msiexec.exe -Args "/I C:\Temp\AzCmdlets\AzCmdlets.msi /quiet /norestart" -Wait
#>


#Disconnect all existing Azure connections
do{
  Disconnect-AzAccount
  $azureContext = Get-AzContext
    }
until (!$azureContext)

Start-Sleep -s 5

Import-Module -Name Az
Connect-AzAccount

Start-Sleep -s 5

Import-Module AzureADPreview
Connect-AzureAD

$subscriptions = Get-AzSubscription | Select-Object -ExpandProperty Id

$Domain = Get-AzureADDomain | where {($_.name -like '*.onmicrosoft.com')}
$Onmicrosoft = $Domain.Name
$InitialDomain = $Onmicrosoft -replace ".onmicrosoft.com", ""

#SecurityGroupNameSFDSSEC
$SecurityGroupNameSFDSSEC = "Global Tenant Administrators"

#SecurityGroupNameSFDSSC
$SecurityGroupNameSFDSSC = "FSLogix_Share_Contributor"

#ResourceName
$resourceGroupName = "Storage_$InitialDomain"

#Location
$location = "westeurope"

#StorageAccountName
$storageAccountName = "$InitialDomain$(Get-Random -Minimum 1000 -Maximum 9999)"

#shareName
$shareName = "fslogix"

#$FileShareSize
$FileShareSize = "1000"

#Activate rights on Azure AD Group variables
$SFDSSC = Get-AzRoleDefinition "Storage File Data SMB Share Contributor"
$SFDSSEC = Get-AzRoleDefinition "Storage File Data SMB Share Elevated Contributor"

$scope = "/subscriptions/$subscriptions/resourceGroups/$resourceGroupName/providers/Microsoft.Storage/storageAccounts/$storageAccountName/fileServices/default/fileshares/$shareName"

# Make sure that tenant administrators have the correct job title
$Admins = Get-AzureADDirectoryRoleMember -ObjectId (Get-AzureADDirectoryRole |? {$_.DisplayName -eq "Global Administrator"}).ObjectId | Select ObjectId, DisplayName
ForEach ($Admin in $Admins) {If ($Admin.DisplayName -ne "Microsoft Rights Management Services") {Set-AzureADUser -Object $Admin.ObjectId -JobTitle "Global Administrator" }}

# First, retrieve the object ID of the 'Global Tenant Administrators' group.
if ($null -eq ((Get-AzureADGroup -Filter "DisplayName eq '$SecurityGroupNameSFDSSEC'")).objectId) {
  $NEWSecurityGroupNameSFDSSEC = New-AzureADMSGroup -DisplayName "$SecurityGroupNameSFDSSEC" -Description "Dynamic Azure 365 Group for all the global tenant administrators" -MailEnabled $False -SecurityEnabled $True -MailNickName GlobalAdmins -GroupTypes "DynamicMembership" -MembershipRule "(User.JobTitle -eq ""Global Administrator"")" -MembershipRuleProcessingState "On"
  }
else {
  Write-Output "Global Tenant Administrators group already exists."
}

#Create a Azure AD Group for FSLogix Share Contributor
if ($null -eq ((Get-AzureADGroup -Filter "DisplayName eq '$SecurityGroupNameSFDSSC'")).objectId) {
  $NEWSecurityGroupNameSFDSSC = New-AzureADMSGroup -DisplayName $SecurityGroupNameSFDSSC -Description $SecurityGroupNameSFDSSC -MailEnabled $false -SecurityEnabled $true -MailNickname $SecurityGroupNameSFDSSC -GroupTypes "DynamicMembership" -MembershipRule 'All users' -MembershipRuleProcessingState "On"
  }
else {
  Write-Output "FSLogix Share Contributor group already exists."
}

$objectIdSFDSSEC = (Get-AzureADGroup -Filter "DisplayName eq '$SecurityGroupNameSFDSSEC'").objectId

$objectIdSFDSSC = (Get-AzureADGroup -Filter "DisplayName eq '$SecurityGroupNameSFDSSC'").objectId

# Create a new Resource Group
if ($null -eq (Get-AzResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue)) {
    New-AzResourceGroup -Name $resourceGroupName -Location $location
}

#Premium_LRS or Standard_LRS
$Standard_LRS = New-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName -Location "westeurope" -SkuName Standard_LRS -Kind StorageV2 -EnableAzureActiveDirectoryDomainServicesForFile $true
#$Premium_LRS = New-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName -Location "westeurope" -SkuName Premium_LRS -Kind FileStorage -EnableAzureActiveDirectoryDomainServicesForFile $true

# Obtain Account Key for new Storage Account
$storageKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[0]

# Set context to new Storage Account
$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageKey

# Create new File Share within the Storage Account
New-AzStorageShare -Name $shareName -Context $storageContext

# Resize the newly created File Share
Set-AzStorageShareQuota -ShareName $shareName -Context $storageContext -Quota $FileShareSize

# Set rights on Share With Azure AD Group
New-AzRoleAssignment -ObjectId $objectIdSFDSSC -RoleDefinitionName $SFDSSC.Name -Scope $scope
New-AzRoleAssignment -ObjectId $objectIdSFDSSEC -RoleDefinitionName $SFDSSEC.Name -Scope $scope

$NetUseNTFS = "\\$storageAccountName.file.core.windows.net\$shareName"
#$NetUseNTFS
#$storageAccountName
#$storageKey
net use Z: $NetUseNTFS /user:Azure\$storageAccountName $storageKey
icacls Z: /remove "NT AUTHORITY\SYSTEM"
icacls Z: /remove "NT AUTHORITY\Geverifieerde gebruikers"
icacls Z: /remove "INGEBOUWD\Gebruikers"
icacls Z: /remove "MAKER EIGENAAR"
icacls Z: /grant:r "INGEBOUWD\Gebruikers:(M)"
icacls Z: /grant:r "MAKER EIGENAAR:(OI)(CI)(IO)(M)"
$NetUseNTFS

#$urldocs = "https://docs.microsoft.com/en-us/fslogix/fslogix-storage-config-ht"