#!/usr/bin/env bash
# Run on an authorised support computer connected to the client's Vega Fire TV.
set -euo pipefail
APP_NAME='Khodi TV Colorful 10B — Vega OS Fire Stick version'
APP_ID='tv.khodi.vega'
COMPONENT='tv.khodi.vega.main'
BUILD='19'
RELEASE_URL='https://www.khoditechsolutions.ca/vega/Khodi-Colorful-10B-Vega-OS-Fire-Stick-1.0.0-build19.vpkg'
RELEASE_SHA256='265228a3c11516799c2884ca3dd98190d1c0b97c492d0c93f069693b99cf888a'
VEGA_BIN="${VEGA_BIN:-vega}"

die() { printf 'Khodi: %s\n' "$*" >&2; exit 1; }
[[ $# -eq 1 && "$1" =~ ^[A-Za-z0-9._:-]+$ ]] || die 'Usage: bash install-khodi-vega.sh CLIENT_SERIAL'
serial="$1"
command -v "$VEGA_BIN" >/dev/null 2>&1 || die 'Install the Amazon Vega SDK and add vega to PATH first.'
command -v curl >/dev/null 2>&1 || die 'curl is required.'
command -v python3 >/dev/null 2>&1 || die 'Python 3 is required to check the device information.'
if command -v shasum >/dev/null 2>&1; then
  hash_file() { shasum -a 256 "$1"; }
elif command -v sha256sum >/dev/null 2>&1; then
  hash_file() { sha256sum "$1"; }
else
  die 'Install shasum or sha256sum to verify the download.'
fi
[[ "$RELEASE_SHA256" =~ ^[a-f0-9]{64}$ ]] || die 'This installer has not been packaged with a verified release.'
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/khodi-vega.XXXXXX")"
trap 'rm -rf "$temp_dir"' EXIT
printf '%s\nChecking connected device %s…\n' "$APP_NAME" "$serial"
"$VEGA_BIN" device info --device "$serial" > "$temp_dir/device.json" || die 'Device is not reachable. Check the client-side USB/network connection and Developer Mode.'
python3 - "$temp_dir/device.json" <<'PY' || exit 1
import json, sys
try:
    device = json.load(open(sys.argv[1]))
    assert device.get('os') == 'vega', 'Use the Android APK for Android / Fire OS devices.'
    assert device.get('inDeveloperMode') is True, 'Enable and authorise Developer Mode on the client device first.'
    assert device.get('simulated') is False, 'This installer is for a physical Fire TV, not the simulator.'
    assert device.get('architecture') in ('armv7', 'armv7l'), 'This package requires an ARMv7 Vega Fire TV.'
except (ValueError, OSError, AssertionError) as error:
    sys.exit('Khodi: ' + str(error))
PY
printf 'Downloading verified Khodi build %s…\n' "$BUILD"
package="$temp_dir/khodi-vega.vpkg"
curl --fail --show-error --silent --location --proto '=https' --tlsv1.2 \
  --retry 3 --connect-timeout 15 --max-time 600 "$RELEASE_URL" --output "$package" \
  || die 'Download failed. Nothing was installed.'
actual="$(hash_file "$package")"; actual="${actual%% *}"
[[ "$actual" == "$RELEASE_SHA256" ]] || die 'Checksum mismatch. Nothing was installed; download again or contact Khodi support.'
"$VEGA_BIN" device install-app --device "$serial" --packagePath "$package" || die 'Installation failed. Check storage, Developer Mode and the installed version.'
"$VEGA_BIN" exec vda -s "$serial" shell "vpm info $APP_ID" > "$temp_dir/installed.txt" || die 'Could not verify the installed package.'
python3 - "$temp_dir/installed.txt" "$BUILD" <<'PY' || exit 1
import re, sys
text = open(sys.argv[1]).read()
match = re.search(r'^build number:\s*(\d+)', text, re.M)
if not match or match[1] != sys.argv[2]:
    sys.exit('Khodi: Installed build could not be verified. Launch was stopped.')
PY
"$VEGA_BIN" device launch-app --device "$serial" --appName "$COMPONENT" || die 'Installed successfully, but launch failed. Open Khodi TV from the Fire TV home screen.'
printf 'Khodi build %s installed and launched on %s. Complete Khodi pairing on the TV.\n' "$BUILD" "$serial"
