# Ethernet Bridge Connector — professional Windows installer (fallback when Setup.exe is not built)
# Creates Program Files install, Start Menu + Desktop shortcuts (with app icon),
# and Add/Remove Programs entry.

$ErrorActionPreference = 'Stop'
$Version = '1.3.0'
$AppName = 'Ethernet Bridge Connector'
$Publisher = 'OneDevMCA'
$InstallDir = Join-Path $env:ProgramFiles 'EthernetBridgeConnector'
$AppSrc = Join-Path $PSScriptRoot 'App'
$ExeName = 'EthernetBridgeConnector.exe'
$ExePath = Join-Path $InstallDir $ExeName
$UninstallKey = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\EthernetBridgeConnector'
$StartMenuDir = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\Ethernet Bridge Connector'
$DesktopLnk = Join-Path ([Environment]::GetFolderPath('Desktop')) "$AppName.lnk"

function Write-Step([string]$msg) {
    Write-Host ""
    Write-Host ">> $msg" -ForegroundColor Cyan
}

Clear-Host
Write-Host "==============================================" -ForegroundColor Blue
Write-Host "  $AppName" -ForegroundColor White
Write-Host "  Setup  v$Version" -ForegroundColor DarkGray
Write-Host "==============================================" -ForegroundColor Blue
Write-Host ""

# Admin check
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "ERROR: Administrator rights are required." -ForegroundColor Red
    Write-Host "Right-click Setup.bat and choose Run as administrator." -ForegroundColor Yellow
    Read-Host "Press Enter to exit"
    exit 1
}

if (-not (Test-Path (Join-Path $AppSrc $ExeName))) {
    Write-Host "ERROR: App files missing. Re-download the installer package." -ForegroundColor Red
    Read-Host "Press Enter to exit"
    exit 1
}

Write-Step "Stopping any running instance..."
Get-Process -Name 'EthernetBridgeConnector' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Milliseconds 400

Write-Step "Installing to $InstallDir"
if (Test-Path $InstallDir) {
    Remove-Item -LiteralPath $InstallDir -Recurse -Force -ErrorAction SilentlyContinue
}
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null

Write-Step "Copying application files..."
Copy-Item -Path (Join-Path $AppSrc '*') -Destination $InstallDir -Recurse -Force

# Ensure icon sits next to exe for shortcut IconLocation fallback
$IconSrc = Join-Path $AppSrc 'Assets\icon.ico'
if (-not (Test-Path $IconSrc)) { $IconSrc = Join-Path $PSScriptRoot 'Assets\icon.ico' }
if (Test-Path $IconSrc) {
    Copy-Item $IconSrc (Join-Path $InstallDir 'icon.ico') -Force
}

Write-Step "Creating Start Menu and Desktop shortcuts..."
if (-not (Test-Path $StartMenuDir)) {
    New-Item -ItemType Directory -Path $StartMenuDir -Force | Out-Null
}

$shell = New-Object -ComObject WScript.Shell
$iconPath = if (Test-Path (Join-Path $InstallDir 'icon.ico')) {
    Join-Path $InstallDir 'icon.ico'
} else {
    $ExePath
}

$sm = $shell.CreateShortcut((Join-Path $StartMenuDir "$AppName.lnk"))
$sm.TargetPath = $ExePath
$sm.WorkingDirectory = $InstallDir
$sm.Description = 'Serial over Ethernet GSM modem bridge'
$sm.IconLocation = "$iconPath,0"
$sm.Save()

$desk = $shell.CreateShortcut($DesktopLnk)
$desk.TargetPath = $ExePath
$desk.WorkingDirectory = $InstallDir
$desk.Description = 'Serial over Ethernet GSM modem bridge'
$desk.IconLocation = "$iconPath,0"
$desk.Save()

# Uninstaller script
$UninstallPs1 = Join-Path $InstallDir 'Uninstall.ps1'
@'
$ErrorActionPreference = "SilentlyContinue"
$InstallDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$AppName = "Ethernet Bridge Connector"
Get-Process -Name "EthernetBridgeConnector" | Stop-Process -Force
Start-Sleep -Milliseconds 300
Remove-Item -LiteralPath "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\Ethernet Bridge Connector" -Recurse -Force
Remove-Item -LiteralPath (Join-Path ([Environment]::GetFolderPath("Desktop")) "$AppName.lnk") -Force
Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\EthernetBridgeConnector" -Recurse -Force
Remove-Item -LiteralPath $InstallDir -Recurse -Force
Write-Host "Uninstalled $AppName."
'@ | Set-Content -Path $UninstallPs1 -Encoding UTF8

$UninstallBat = Join-Path $InstallDir 'Uninstall.bat'
@"
@echo off
net session >nul 2>&1
if %errorLevel% neq 0 (
  powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
  exit /b
)
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0Uninstall.ps1"
pause
"@ | Set-Content -Path $UninstallBat -Encoding ASCII

Write-Step "Registering in Apps & Features..."
$estimated = [int]((Get-ChildItem $InstallDir -Recurse -File | Measure-Object Length -Sum).Sum / 1KB)
New-Item -Path $UninstallKey -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'DisplayName' -Value $AppName -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'DisplayVersion' -Value $Version -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'Publisher' -Value $Publisher -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'InstallLocation' -Value $InstallDir -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'DisplayIcon' -Value "$ExePath,0" -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'UninstallString' -Value "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$UninstallPs1`"" -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'QuietUninstallString' -Value "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$UninstallPs1`"" -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'EstimatedSize' -Value $estimated -PropertyType DWord -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'NoModify' -Value 1 -PropertyType DWord -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'NoRepair' -Value 1 -PropertyType DWord -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'URLInfoAbout' -Value 'https://onedevmca.com' -PropertyType String -Force | Out-Null
New-ItemProperty -Path $UninstallKey -Name 'HelpLink' -Value 'https://onedevmca.com' -PropertyType String -Force | Out-Null

Write-Host ""
Write-Host "==============================================" -ForegroundColor Blue
Write-Host "  Installation complete" -ForegroundColor Green
Write-Host "==============================================" -ForegroundColor Blue
Write-Host ""
Write-Host "  Installed to:  $InstallDir"
Write-Host "  Shortcuts:     Start Menu + Desktop (with app icon)"
Write-Host "  Uninstall:     Windows Settings → Apps, or Uninstall.bat"
Write-Host ""

$launch = Read-Host "Launch $AppName now? (Y/N)"
if ($launch -match '^[Yy]') {
    Start-Process -FilePath $ExePath -WorkingDirectory $InstallDir
}

exit 0
