[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$kitRoot = Split-Path -Parent $PSScriptRoot
$adb = Join-Path $kitRoot 'platform-tools\adb.exe'

Write-Host 'TECHNOZON X11 - rotate TV SMB pairing' -ForegroundColor Cyan
Write-Host 'Connect exactly one NEXON X11 over USB ADB.'
if ((Read-Host 'Type ROTATE to invalidate the current pairing') -ne 'ROTATE') {
    exit 2
}

$serials = @(& $adb devices | Select-Object -Skip 1 | ForEach-Object {
    if ($_ -match '^(\S+)\s+device$') { $matches[1] }
})
if ($serials.Count -ne 1) {
    throw 'Exactly one USB ADB device must be online.'
}
$serial = $serials[0]
$device = ((& $adb -s $serial shell getprop ro.product.device) -join '').Trim()
$incremental = ((& $adb -s $serial shell getprop ro.build.version.incremental) -join '').Trim()
if ($device -ne 'ross' -or $incremental -ne '250926144031') {
    throw "Wrong device: device=$device incremental=$incremental"
}

$command = @'
set -eu
DATA=/data/adb/tvsmbmanager
umask 077
mkdir -p "$DATA"
dd if=/dev/urandom of="$DATA/license.bin" bs=32 count=1 2>/dev/null
dd if=/dev/urandom of="$DATA/install.id" bs=16 count=1 2>/dev/null
printf 1 > "$DATA/contract.version"
chown 0:0 "$DATA/license.bin" "$DATA/install.id" "$DATA/contract.version"
chmod 600 "$DATA/license.bin" "$DATA/install.id" "$DATA/contract.version"
if [ -f "$DATA/run/smbd.pid" ]; then
  kill "$(cat "$DATA/run/smbd.pid")" 2>/dev/null || true
  rm -f "$DATA/run/smbd.pid"
fi
test "$(stat -c '%u:%g:%a:%s' "$DATA/license.bin")" = "0:0:600:32"
test "$(stat -c '%u:%g:%a:%s' "$DATA/install.id")" = "0:0:600:16"
test "$(stat -c '%u:%g:%a:%s' "$DATA/contract.version")" = "0:0:600:1"
echo TVSMB_PAIRING_ROTATED
'@

$output = @(& $adb -s $serial shell su 0 sh -c $command 2>&1)
if ($LASTEXITCODE -ne 0 -or ($output -join "`n") -notmatch 'TVSMB_PAIRING_ROTATED') {
    $output | Out-Host
    throw 'Pairing rotation failed.'
}

& $adb -s $serial shell am force-stop info.technozon.tvsmbmanager | Out-Null
& $adb -s $serial shell am force-stop info.technozon.steshmodifier | Out-Null
Write-Host 'Pairing rotated. Reboot the TV box before using TV SMB Manager.' -ForegroundColor Green
