# Readable build source. Customer launcher embeds these static commands; it does not load this file.
Set-StrictMode -Version 2;
$ErrorActionPreference='Stop';
$pkg='com.byd.appstartmanagement';
function One($t,$r){$m=[regex]::Matches($t,$r);if($m.Count -ne 1){throw 'AMBIGUOUS_OR_MISSING_EVIDENCE'};return $m[0].Groups[1].Value;};
function Ip($t){if($t -notmatch '^(10|172|192)\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'){throw 'PRIVATE_IPV4_REQUIRED'};$o=@($t.Split('.')|ForEach-Object{[int]$_});foreach($v in $o){if($v -gt 255){throw 'PRIVATE_IPV4_REQUIRED'}};if(($o -join '.') -cne $t -or -not($o[0] -eq 10 -or ($o[0] -eq 172 -and $o[1] -ge 16 -and $o[1] -le 31) -or ($o[0] -eq 192 -and $o[1] -eq 168))){throw 'PRIVATE_IPV4_REQUIRED'};return $t;};
function ApkPath($t){$lines=@($t.Replace([string][char]13,'').Split([char]10)|Where-Object{$_.Trim()});if($lines.Count -ne 1){throw 'MISSING_OR_SPLIT_PACKAGE'};$p=One $lines[0] '^package:(/[A-Za-z0-9_./+=~-]+\.apk)$';if($p -match '(^|/)\.\.(/|$)' -or $p -notmatch '^/(?:(?:system|system_ext|product|vendor)/(?:priv-app|app)/|data/app/)'){throw 'UNSUPPORTED_APK_PATH'};return $p;};
function Meta($t){$t=$t.Replace([string][char]13,'');$b=One $t '(?ms)^  Package \[com\.byd\.appstartmanagement\] \([^\n]+\):\n(.*?)(?=^  Package \[|^\S|\z)';$flags=One $b '(?m)^    flags=\[([^\r\n]+)\] *$';if($flags -notmatch '(?:^|\s)(?:SYSTEM|UPDATED_SYSTEM_APP)(?:\s|$)'){throw 'NOT_SYSTEM_MANAGER'};$u=One $b '(?m)^    User 0: ([^\n]+)$';if((One $u '(?:^| )installed=(true|false)(?: |$)') -ne 'true'){throw 'NOT_INSTALLED_FOR_USER0'};return [ordered]@{package=$pkg;version_code=[long](One $b '(?m)^    versionCode=(\d+)\b[^\n]*$');version_name=One $b '(?m)^    versionName=([^\n]{1,160})$';system_flags=$flags;user=0;installed=$true};};
function Native($exe,$argsList,$seconds=20,$cap=1048576){$pi=New-Object Diagnostics.ProcessStartInfo;$pi.FileName=$exe;$q=[string][char]34;$parts=@();foreach($a in $argsList){if($a.Contains($q)){throw 'UNSAFE_ARGUMENT'};$parts+=($q+$a+$q)};$pi.Arguments=$parts -join ' ';$pi.UseShellExecute=$false;$pi.CreateNoWindow=$true;$pi.RedirectStandardOutput=$true;$pi.RedirectStandardError=$true;$p=New-Object Diagnostics.Process;$p.StartInfo=$pi;$ss=@();$buf=@();$tasks=@();$ended=@($false,$false);$mem=New-Object IO.MemoryStream;$watch=[Diagnostics.Stopwatch]::StartNew();try{if(-not $p.Start()){throw 'PROCESS_START_FAILED'};$ss=@($p.StandardOutput.BaseStream,$p.StandardError.BaseStream);for($i=0;$i -lt 2;$i++){$buf+=,(New-Object byte[] 8192);$tasks+=,($ss[$i].ReadAsync($buf[$i],0,8192))};$total=0;while(-not $ended[0] -or -not $ended[1]){if($watch.Elapsed.TotalSeconds -gt $seconds){throw 'COMMAND_TIMEOUT'};for($i=0;$i -lt 2;$i++){if(-not $ended[$i] -and $tasks[$i].IsCompleted){$n=$tasks[$i].GetAwaiter().GetResult();$total+=$n;if($total -gt $cap){throw 'OUTPUT_LIMIT'};if($n -eq 0){$ended[$i]=$true}else{if($i -eq 0){$mem.Write($buf[$i],0,$n)};$tasks[$i]=$ss[$i].ReadAsync($buf[$i],0,8192)}}};[Threading.Thread]::Sleep(10)};if(-not $p.WaitForExit(1000)){throw 'COMMAND_TIMEOUT'};if($p.ExitCode -ne 0){throw 'COMMAND_FAILED_OR_DENIED'};return ([Text.Encoding]::UTF8.GetString($mem.ToArray())).Trim()}finally{try{if(-not $p.HasExited){$p.Kill();[void]$p.WaitForExit(1000)}}catch{};foreach($s in $ss){$s.Dispose()};$mem.Dispose();$p.Dispose()};};
function Adb($a,$seconds=20,$cap=1048576){return Native $script:adb (@('-H','127.0.0.1','-P','5037')+$a) $seconds $cap;};
function Device($a){return Adb (@('-s',$script:target,'shell','-T')+$a);};
function HashDevice($path){return (One (Device @('sha256sum',$path)) ('^([a-fA-F0-9]{64})\s+'+[regex]::Escape($path)+'$')).ToLowerInvariant();};
# ENTRYPOINT
$folder=$null;
try{
$base=$env:SWM_COLLECTOR_ROOT;if(-not $base -or -not [IO.Directory]::Exists($base)){throw 'EXTRACT_ALL_FIRST'};
$tools=Join-Path $base 'platform-tools';$pins=@{'adb.exe'='b4a6b455702684652cccf7b46258b29e653538904359a58fd4931cf3ef286b3f';'AdbWinApi.dll'='c1d653030b4bde65d3e07e4d0b0979e17be56df1436cdd15528630f27808050d';'AdbWinUsbApi.dll'='0710e894d9b40f71a670c13c694079d564c92c1279da382cfe4850983aaebe1b'};foreach($n in $pins.Keys){if((Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $tools $n)).Hash.ToLowerInvariant() -cne $pins[$n]){throw 'TOOLS_MISSING_OR_CHANGED'}};$script:adb=Join-Path $tools 'adb.exe';
Write-Host 'Read-only BYD startup-manager APK collection. No apps/settings are changed. No automatic upload.';
$ip=(Read-Host 'Current Shark private IPv4 address (no port); blank cancels').Trim();if(-not $ip){Write-Host 'CANCELLED - nothing collected';exit 0};$script:target=(Ip $ip)+':5555';if((Read-Host 'Park safely. Type COLLECT to connect and copy only the startup-manager APK') -cne 'COLLECT'){Write-Host 'CANCELLED - nothing collected';exit 0};
$leaf='SW-Manager-Evidence-'+[DateTime]::UtcNow.ToString('yyyyMMdd-HHmmss')+'-'+[Guid]::NewGuid().ToString('N').Substring(0,8);$folder=Join-Path $base $leaf;[void][IO.Directory]::CreateDirectory($folder);$result=Join-Path $folder 'COLLECTION-RESULT.txt';[IO.File]::WriteAllText($result,'STATUS=INCOMPLETE');
[void](Adb @('connect',$script:target) 15);if((Adb @('-s',$script:target,'get-state')) -cne 'device'){throw 'DEVICE_NOT_AUTHORIZED_OR_OFFLINE'};
$model=Device @('getprop','ro.product.model');$brand=Device @('getprop','ro.product.manufacturer');$sdk=Device @('getprop','ro.build.version.sdk');$user=Device @('am','get-current-user');if($model -notin @('BYD AUTO','BYD_AUTO') -or $brand -notin @('BYD','BYDAuto') -or $sdk -cne '30' -or $user -cne '0'){throw 'UNSUPPORTED_DEVICE_OR_USER'};
$boot=One (Device @('cat','/proc/sys/kernel/random/boot_id')) '^([0-9a-fA-F-]{36})$';$path=ApkPath (Device @('pm','path','--user','0',$pkg));$metadata=Meta (Device @('dumpsys','package',$pkg));$size=[long](One (Device @('stat','-c',([string][char]37+'s'),$path)) '^(\d{1,9})$');if($size -lt 1024 -or $size -gt 134217728){throw 'APK_SIZE_OUT_OF_BOUNDS'};$before=HashDevice $path;
$apk=Join-Path $folder 'BydAppStartManagement.apk';[void](Adb @('-s',$script:target,'pull',$path,$apk) 600 524288);if((Get-Item -LiteralPath $apk).Length -ne $size){throw 'APK_SIZE_MISMATCH'};$local=(Get-FileHash -Algorithm SHA256 -LiteralPath $apk).Hash.ToLowerInvariant();if($local -cne $before -or (HashDevice $path) -cne $before){throw 'APK_HASH_MISMATCH'};
if((Device @('cat','/proc/sys/kernel/random/boot_id')) -cne $boot -or (Device @('am','get-current-user')) -cne '0' -or (ApkPath (Device @('pm','path','--user','0',$pkg))) -cne $path){throw 'DEVICE_OR_PACKAGE_CHANGED'};
Add-Type -AssemblyName System.IO.Compression.FileSystem;$z=[IO.Compression.ZipFile]::OpenRead($apk);try{if($z.Entries.Count -gt 10000 -or -not $z.GetEntry('AndroidManifest.xml') -or -not $z.GetEntry('classes.dex')){throw 'INVALID_APK_CONTAINER'}}finally{$z.Dispose()};
$metadata.apk_sha256=$local;$metadata.apk_bytes=$size;$metadata.collection_utc=[DateTime]::UtcNow.ToString('o');$metadata.model=$model;$metadata.manufacturer=$brand;$metadata.android_sdk=30;$metadata.hashes_verified=$true;$metadata.automatic_upload=$false;$metadata | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $folder 'MANIFEST.json') -Encoding UTF8;
[IO.File]::WriteAllText($result,'STATUS=COMPLETE - exact device/local APK hash and size matched. No automatic upload.');Write-Host 'COMPLETE. Review the manifest and decide whether/how to return this folder:';Write-Host $folder;exit 0;
}catch{if($folder){[IO.File]::WriteAllText((Join-Path $folder 'COLLECTION-RESULT.txt'),'STATUS=INCOMPLETE - keep partial evidence; do not treat APK as verified.')};Write-Host 'STOP. Collection incomplete. No app/settings were changed. Do not rerun blindly or bypass security warnings.';Write-Host $_.Exception.Message;exit 1;};
