
&"$PSScriptRoot\vars.ps1"
&"$PSScriptRoot\check-administrator.ps1"
&"$PSScriptRoot\fn-php.ps1"

$Existing = Get-PhpIniKey "session.save_path" $PHPdir

$TempDir = Read-Host "Where do you want to move the temp files? Enter directory (e.g. C:\inetpub\php\temp\)"
if (($TempDir -eq '')) {
    Write-Error "TempDir must be a relative or absolute path"
    exit
}

# Create folder if not exists:
if (-Not (Test-Path -Path $TempDir)) {
    Write-Output "Creating $TempDir - does not exist"
    New-Item -Path $TempDir -ItemType "directory" | Out-Null
}

# Check folder empty:
if ((Get-ChildItem -Path $TempDir -Recurse | Measure-Object).Count) {
    Write-Error "$TempDir is not empty"
    exit
}

# Allow full control on new temp folder for IIS user:
Write-Output "Updating security permissions"

$IISUser = Read-Host "User for IIS (e.g. IUSR)"

try {
    $Acl = Get-Acl $TempDir
    $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($IISUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
    $Acl.SetAccessRule($AccessRule)
    Set-Acl $TempDir $Acl -ErrorAction Stop 
} catch {
    Write-Error "Error modifying permissions - are you running as Administrator?"
    exit
}

# Update INI settings
Write-Output "Updating PHP.ini Settings"

Set-PhpIniKey  "session.save_path" $TempDir $PHPdir
Set-PhpIniKey  "upload_tmp_dir" $TempDir $PHPdir

# Move exsiting `sess_` files
Write-Output "Moving existing sessions"
Get-ChildItem -Path "$Existing\sess_*" -Recurse | Move-Item -Destination $TempDir

Write-Output "Done"