#!/usr/bin/env bash
#
# GasPro launcher - single-device ADB provisioning (macOS / Linux).
#
# Installs the launcher, makes it the default home, and sets it as Device Owner,
# in the required order (Device Owner LAST - it disables USB debugging).
#
# Prerequisites: adb on PATH; a FACTORY-RESET device with NO account added and
# USB debugging enabled, connected over USB.
#
# Usage:
#   ./provision-device.sh            # provisions the single connected device
#   ./provision-device.sh ABC123     # target a specific device serial
set -euo pipefail

APK_URL="${APK_URL:-https://gaspro-launcher.pages.dev/app-release.apk}"
APK_PATH="${APK_PATH:-app-release.apk}"
COMPONENT="cr.gaspro.launcher/.receiver.GasProDeviceAdminReceiver"
HOME_ACTIVITY="cr.gaspro.launcher/.LauncherActivity"
SERIAL="${1:-}"

command -v adb >/dev/null 2>&1 || { echo "adb not found on PATH. Install Android platform-tools."; exit 1; }

# Collect authorized ('device') serials.
devices=()
while IFS= read -r line; do
  [[ -n "$line" ]] && devices+=("$line")
done < <(adb devices | awk 'NR>1 && $2=="device" {print $1}')

if [[ -n "$SERIAL" ]]; then
  printf '%s\n' "${devices[@]}" | grep -qx -- "$SERIAL" || {
    echo "Device '$SERIAL' not connected/authorized. Connected: ${devices[*]:-none}"; exit 1; }
elif [[ ${#devices[@]} -eq 0 ]]; then
  echo "No authorized device found. Check cable, USB debugging, and the 'Allow USB debugging?' prompt."; exit 1
elif [[ ${#devices[@]} -gt 1 ]]; then
  echo "Multiple devices connected (${devices[*]}). Re-run: ./provision-device.sh <serial>"; exit 1
else
  SERIAL="${devices[0]}"
fi
echo "Target device: $SERIAL"

if [[ ! -f "$APK_PATH" ]]; then
  echo "Downloading APK from $APK_URL ..."
  curl -L -o "$APK_PATH" "$APK_URL"
fi

echo "[1/3] Installing launcher..."
adb -s "$SERIAL" install -r "$APK_PATH"

echo "[2/3] Setting GasPro as the default launcher..."
adb -s "$SERIAL" shell cmd package set-home-activity "$HOME_ACTIVITY"

echo "[3/3] Setting Device Owner (device disconnects from adb right after)..."
out="$(adb -s "$SERIAL" shell dpm set-device-owner "$COMPONENT" 2>&1 || true)"
echo "$out"
case "$out" in
  *Success*) ;;
  *) echo "ERROR: set-device-owner did not report success. Most common cause: an account is on the device - factory reset, skip all sign-in, then retry."; exit 1 ;;
esac

echo
echo "Done - $SERIAL is now Device Owner with GasPro as the launcher."
echo "It has dropped off adb (USB debugging disabled by kiosk policy) - this is expected."
echo "Press Home or reboot the device to activate the kiosk."
