param(
    [string]$SourceDir = ''
)

$ErrorActionPreference = 'Stop'

$productName = 'DotClean'
$installDir = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'QingWenTang\Scripts\tichuyoulidia'
$exeName = 'DotClean.exe'
$jsxName = 'RemoveFloatingDots_CurrentLayer.jsx'
$psMenuScriptName = 'QingWenTang_DotClean.jsx'

function Test-Admin {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Relaunch-AsAdmin {
    $scriptPath = $PSCommandPath
    $sourceDir = Split-Path -Parent $scriptPath
    $args = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$scriptPath`"", '-SourceDir', "`"$sourceDir`"")
    Start-Process -FilePath 'powershell.exe' -ArgumentList $args -Verb RunAs
}

if ([string]::IsNullOrWhiteSpace($SourceDir)) {
    $SourceDir = Split-Path -Parent $PSCommandPath
}

if (-not (Test-Admin)) {
    Relaunch-AsAdmin
    exit
}

if (-not (Test-Path -LiteralPath (Join-Path $SourceDir $exeName))) {
    throw "$exeName was not found. Please run this installer from the published DotClean folder."
}

New-Item -ItemType Directory -Path $installDir -Force | Out-Null

Get-ChildItem -LiteralPath $SourceDir -File | ForEach-Object {
    if ($_.Name -notin @('Install-DotClean.ps1', 'Install-DotClean.bat', '一键安装_DotClean.bat')) {
        Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $installDir $_.Name) -Force
    }
}

$desktop = [Environment]::GetFolderPath('DesktopDirectory')
$shortcutPath = Join-Path $desktop "$productName.lnk"
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = Join-Path $installDir $exeName
$shortcut.WorkingDirectory = $installDir
$shortcut.IconLocation = Join-Path $installDir $exeName
$shortcut.Description = $productName
$shortcut.Save()

$documentsJsx = Join-Path $installDir $jsxName
if (-not (Test-Path -LiteralPath $documentsJsx)) {
    throw "$jsxName was not found. Photoshop script installation is incomplete."
}

$photoshopScriptsDirs = @()
$adobeRoots = @(
    (Join-Path $env:ProgramFiles 'Adobe'),
    (Join-Path ${env:ProgramFiles(x86)} 'Adobe')
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }

foreach ($root in $adobeRoots) {
    $photoshopScriptsDirs += Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -like 'Adobe Photoshop*' } |
        ForEach-Object { Join-Path $_.FullName 'Presets\Scripts' } |
        Where-Object { Test-Path -LiteralPath $_ }
}

if ($photoshopScriptsDirs.Count -gt 0) {
    $targetScriptsDir = $photoshopScriptsDirs |
        Sort-Object { (Get-Item -LiteralPath $_).LastWriteTime } -Descending |
        Select-Object -First 1

    $stubPath = Join-Path $targetScriptsDir $psMenuScriptName
    $stubContent = @'
#target photoshop

(function () {
    var target = new File(Folder.myDocuments.fsName + "/QingWenTang/Scripts/tichuyoulidia/RemoveFloatingDots_CurrentLayer.jsx");
    if (!target.exists) {
        alert("DotClean Photoshop script was not found:\n" + target.fsName + "\n\nPlease run the DotClean installer again.");
        return;
    }
    $.evalFile(target);
})();
'@
    Set-Content -LiteralPath $stubPath -Value $stubContent -Encoding UTF8
    Write-Host "Photoshop script installed: $stubPath"
} else {
    Write-Host "Photoshop installation was not found. Photoshop menu script installation was skipped."
    Write-Host "The app and desktop shortcut were installed."
}

Write-Host ''
Write-Host "Installed to: $installDir"
Write-Host "Desktop shortcut: $shortcutPath"
Write-Host ''
Read-Host 'Press Enter to exit'
