param(
    [string] $Serial
)

$ErrorActionPreference = 'Stop'
$packageName = 'com.ponzischeme89.memby'
$activityName = "$packageName/$packageName.ui.MainActivity"
$jdkHome = 'C:\Program Files\Android\Android Studio\jbr'
$adbPath = Join-Path $env:LOCALAPPDATA 'Android\Sdk\platform-tools\adb.exe'

if (Test-Path $jdkHome) { $env:JAVA_HOME = $jdkHome }
if (-not (Test-Path $adbPath)) { throw "Android Debug Bridge was not found at $adbPath" }

$deviceArgs = if ($Serial) { @('-s', $Serial) } else { @() }
# Stop only Memby before replacing its debug APK.
& $adbPath @deviceArgs shell am force-stop $packageName

& .\gradlew.bat installDebug
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

# Start the new client's launcher after installation.
& $adbPath @deviceArgs shell input keyevent KEYCODE_WAKEUP
& $adbPath @deviceArgs shell am start -W -n $activityName
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
