$ErrorActionPreference = 'Stop'

$sourceRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$sourceEncoders = Join-Path $sourceRoot 'encoders'
$targetEncoders = Join-Path $env:USERPROFILE 'encoders'
$sendTo = [Environment]::GetFolderPath('SendTo')
$sourceManifest = Join-Path $sourceRoot '.sendto.json'
$targetManifest = Join-Path $targetEncoders '.sendto.json'

if (-not (Test-Path -LiteralPath $sourceEncoders)) {
    throw "Could not find encoders folder beside installer: $sourceEncoders"
}

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

$sourceItems = Get-ChildItem -LiteralPath $sourceEncoders -Force
foreach ($item in $sourceItems) {
    $targetPath = Join-Path $targetEncoders $item.Name
    if ($item.Name -ieq 'path.txt' -and (Test-Path -LiteralPath $targetPath)) {
        Write-Host "Keeping existing path.txt at $targetPath"
        continue
    }

    Copy-Item -LiteralPath $item.FullName -Destination $targetPath -Recurse -Force
}

$obsoleteEncoderFiles = @(
    'fpg.bat',
    'youtube-dl.exe',
    'flcnm.bat',
    'flcrnm.bat',
    'flcwavnm.bat',
    'libsndfile-1.dll',
    'neroAacEnc.exe',
    'qtaacenc.exe',
    'test.exe',
    'avcodec-vgmstream-58.dll',
    'avformat-vgmstream-58.dll',
    'avutil-vgmstream-56.dll',
    'swresample-vgmstream-3.dll'
)

$obsoleteEncoderDirs = @(
    'libsndfile'
)

foreach ($file in $obsoleteEncoderFiles) {
    $obsoletePath = Join-Path $targetEncoders $file
    if (Test-Path -LiteralPath $obsoletePath) {
        Remove-Item -LiteralPath $obsoletePath -Force
        Write-Host "Removed obsolete encoder helper $obsoletePath"
    }
}

foreach ($dir in $obsoleteEncoderDirs) {
    $obsoletePath = Join-Path $targetEncoders $dir
    if (Test-Path -LiteralPath $obsoletePath) {
        Remove-Item -LiteralPath $obsoletePath -Recurse -Force
        Write-Host "Removed obsolete encoder directory $obsoletePath"
    }
}

$obsoleteShortcuts = @(
    'FFMP&eg to M4A.lnk'
)

foreach ($name in $obsoleteShortcuts) {
    $obsoletePath = Join-Path $sendTo $name
    if (Test-Path -LiteralPath $obsoletePath) {
        Remove-Item -LiteralPath $obsoletePath -Force
        Write-Host "Removed obsolete SendTo shortcut $obsoletePath"
    }
}

$shortcuts = @(
    @{ Name = '&Flac 2 Wav and delete.lnk'; Target = 'flac.exe'; Args = '-d --delete-input-file --keep-foreign-metadata-if-present -j 4'; WorkDir = '' },
    @{ Name = '&ogg encode.lnk'; Target = 'oggenc2.exe'; Args = '-q4'; WorkDir = '' },
    @{ Name = '&Wav 2 Flac and delete.lnk'; Target = 'flac.exe'; Args = '-8 --delete-input-file -V -f --keep-foreign-metadata-if-present -j 4'; WorkDir = '' },
    @{ Name = 'AA&c encode.lnk'; Target = 'aac.bat'; Args = ''; WorkDir = $targetEncoders },
    @{ Name = 'Fi&le to Wav.lnk'; Target = 'file2wav.bat'; Args = ''; WorkDir = $targetEncoders },
    @{ Name = 'File to &MOV.lnk'; Target = 'file2mov.bat'; Args = ''; WorkDir = $targetEncoders },
    @{ Name = 'File to MP&4.lnk'; Target = 'file2mp4.bat'; Args = ''; WorkDir = $targetEncoders },
    @{ Name = 'file+ima&ge2video.lnk'; Target = 'file+image2video.bat'; Args = ''; WorkDir = $targetEncoders },
    @{ Name = 'mp&3 encode.lnk'; Target = 'mp3.bat'; Args = ''; WorkDir = $targetEncoders },
    @{ Name = 'o&pus decode to wav.lnk'; Target = 'OpDec.bat'; Args = ''; WorkDir = $env:WINDIR },
    @{ Name = 'op&us encode.lnk'; Target = 'opEnc.bat'; Args = ''; WorkDir = $env:WINDIR },
    @{ Name = 'vgmst&reamer.lnk'; Target = 'vgmstreamer.bat'; Args = ''; WorkDir = $targetEncoders }
)

$shell = New-Object -ComObject WScript.Shell
foreach ($item in $shortcuts) {
    $shortcutPath = Join-Path $sendTo $item.Name
    $shortcut = $shell.CreateShortcut($shortcutPath)
    $shortcut.TargetPath = Join-Path $targetEncoders $item.Target
    $shortcut.Arguments = $item.Args
    $shortcut.WorkingDirectory = $item.WorkDir
    $shortcut.Save()
}

$currentUserPath = [Environment]::GetEnvironmentVariable('Path', 'User')
$pathParts = @()
if ($currentUserPath) {
    $pathParts = $currentUserPath -split ';' | Where-Object { $_ -ne '' }
}

$alreadyPresent = $false
foreach ($part in $pathParts) {
    $expanded = [Environment]::ExpandEnvironmentVariables($part)
    if ($expanded.TrimEnd('\') -ieq $targetEncoders.TrimEnd('\')) {
        $alreadyPresent = $true
        break
    }
}

if (-not $alreadyPresent) {
    $pathParts += $targetEncoders
    [Environment]::SetEnvironmentVariable('Path', ($pathParts -join ';'), 'User')
}

if (Test-Path -LiteralPath $sourceManifest) {
    Copy-Item -LiteralPath $sourceManifest -Destination $targetManifest -Force
    Write-Host "Recorded installed SendTo version in $targetManifest"
}

Write-Host "Installed encoders to $targetEncoders"
Write-Host "Installed SendTo shortcuts to $sendTo"
if ($alreadyPresent) {
    Write-Host "$targetEncoders was already present in the user PATH"
} else {
    Write-Host "Added $targetEncoders to the user PATH. Open a new terminal before using it from cmd or PowerShell."
}
