#!/bin/bash
# ─────────────────────────────────────────────────────────────
# Azaan Box — Full Device Provisioning Script
# ─────────────────────────────────────────────────────────────

set -e

APK="android/app/build/outputs/apk/release/app-release.apk"
PACKAGE="com.letsweby.azaanbox"
ADMIN_RECEIVER="$PACKAGE/.DeviceAdminReceiver"
BOOTANIM="bootanimation.zip"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║     Azaan Box — Device Provisioning     ║"
echo "╚══════════════════════════════════════════╝"
echo ""

# ── Build AzaanBox? ───────────────────────────────────────────
read -p "Build a fresh AzaanBox APK? (y/n): " BUILD_CHOICE
if [ "$BUILD_CHOICE" = "y" ] || [ "$BUILD_CHOICE" = "Y" ]; then
  echo -e "${YELLOW}Building AzaanBox release APK...${NC}"
  rm -f android/app/build/generated/assets/createBundleReleaseJsAndAssets/index.android.bundle
  cd android && ./gradlew assembleRelease && cd ..
  echo -e "${GREEN}AzaanBox build complete.${NC}"
else
  echo "Skipping AzaanBox build — using existing APK."
fi

# ── Connect ───────────────────────────────────────────────────
echo ""
echo "How is the device connected?"
echo "  1) USB cable"
echo "  2) WiFi (wireless ADB)"
echo ""
read -p "Enter 1 or 2: " CONNECT_MODE
echo ""

if [ "$CONNECT_MODE" = "1" ]; then
  DEVICE_SERIAL=$(adb devices | awk 'NR>1 && $2=="device" && $1 !~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+$/ {print $1; exit}')
  if [ -z "$DEVICE_SERIAL" ]; then
    echo -e "${RED}No USB device found. Connect via cable and enable USB debugging.${NC}"
    exit 1
  fi
  echo -e "${GREEN}Found USB device: $DEVICE_SERIAL${NC}"
else
  read -p "Device IP (e.g. 10.0.0.249 or 10.0.0.249:46163): " DEVICE_IP
  if echo "$DEVICE_IP" | grep -q ":"; then
    DEVICE_SERIAL="$DEVICE_IP"
  else
    DEVICE_SERIAL="$DEVICE_IP:5555"
  fi
  adb connect "$DEVICE_SERIAL" > /dev/null
  echo -e "${GREEN}Connected to $DEVICE_SERIAL.${NC}"
fi

ADB="adb -s $DEVICE_SERIAL"

# ── Check no Google accounts ──────────────────────────────────
ACCOUNTS=$($ADB shell dumpsys account | grep "Account {" | wc -l | tr -d ' ')
if [ "$ACCOUNTS" -gt "0" ]; then
  echo ""
  echo -e "${RED}ERROR: This device has $ACCOUNTS Google account(s) on it.${NC}"
  echo -e "${RED}Device Owner cannot be set while accounts exist.${NC}"
  echo ""
  echo "  → Factory reset the box and try again."
  echo "  → During setup wizard, SKIP Google sign-in."
  echo ""
  exit 1
fi

# ── Check for old app ─────────────────────────────────────────
OLD_PACKAGE="com.letsweby.masjidbilaltv"
if $ADB shell pm list packages | grep -q "$OLD_PACKAGE"; then
  echo ""
  echo -e "${RED}ERROR: Old app ($OLD_PACKAGE) is installed as Device Owner.${NC}"
  echo -e "${RED}It cannot be uninstalled without a factory reset.${NC}"
  echo ""
  echo "  Run this to factory reset via ADB, then re-run this script:"
  echo "  adb -s $DEVICE_SERIAL shell am broadcast -a android.intent.action.FACTORY_RESET -n \"android/com.android.server.MasterClearReceiver\""
  echo ""
  exit 1
fi

# ── Push boot animation ───────────────────────────────────────
if [ -f "$SCRIPT_DIR/$BOOTANIM" ]; then
  echo ""
  echo -e "${CYAN}Pushing AzaanBox boot animation...${NC}"
  # Restart adb as root so we can write to /system
  $ADB root > /dev/null 2>&1 && sleep 2
  $ADB remount > /dev/null 2>&1 || true
  $ADB push "$SCRIPT_DIR/$BOOTANIM" /system/media/bootanimation.zip
  $ADB shell chmod 644 /system/media/bootanimation.zip
  echo -e "${GREEN}Boot animation installed.${NC}"
else
  echo -e "${YELLOW}bootanimation.zip not found — skipping boot animation.${NC}"
fi

# ── Display settings ─────────────────────────────────────────
echo ""
echo -e "${CYAN}Configuring display settings...${NC}"
$ADB shell settings put system screen_brightness_mode 0   # manual brightness
$ADB shell settings put system screen_brightness 255       # 100% brightness
$ADB shell settings put system adaptive_sleep 0           # disable adaptive sleep
echo -e "${GREEN}Display configured.${NC}"

# ── Automatic date/time ───────────────────────────────────────
# A wrong clock breaks TLS validation of Android's internet probe → box shows
# "Limited connection" even with working internet. Force auto-time + NTP so it stays correct.
echo ""
echo -e "${CYAN}Enabling automatic date/time (prevents 'Limited connection')...${NC}"
$ADB shell settings put global auto_time 1
$ADB shell settings put global auto_time_zone 1
$ADB shell settings put global ntp_server time.google.com
echo -e "${GREEN}Auto date/time enabled.${NC}"

# ── Free up storage ───────────────────────────────────────────
echo ""
echo -e "${CYAN}Freeing up device storage...${NC}"
$ADB root > /dev/null 2>&1 && sleep 2

# ROM zips and flash leftovers left behind after flashing
$ADB shell "rm -f /data/media/0/*.zip /data/media/0/*.img 2>/dev/null" || true
$ADB shell "rm -f /data/media/0/recording.mp4 2>/dev/null" || true
$ADB shell "rm -f /data/media/0/bundle_* /data/media/0/configBundle /data/media/0/deviceConfigBundles /data/media/0/extractedTar /data/media/0/tarBundle 2>/dev/null" || true
$ADB shell "rm -f /data/media/0/*.json /data/media/0/*.dat /data/media/0/*.mp3 2>/dev/null" || true

# Old cached APKs from previous OTA updates
$ADB shell "rm -f /data/data/$PACKAGE/cache/azaanbox_update.apk 2>/dev/null" || true

# Crash dumps (tombstones) — safe to delete, just debug info
$ADB shell "rm -f /data/tombstones/tombstone_* 2>/dev/null" || true

# Old logd logs
$ADB shell "rm -f /data/logd/* 2>/dev/null" || true

# Stuck PackageInstaller sessions from failed/aborted updates
$ADB shell "for SESSION in \$($ADB shell pm list staged-sessions 2>/dev/null | awk '{print \$2}'); do $ADB shell pm install-abandon \$SESSION 2>/dev/null; done" || true

FREE=$($ADB shell df /data 2>/dev/null | awk 'NR==2{printf "%.0f", $4/1024}')
echo -e "${GREEN}Storage freed. Available: ${FREE}MB${NC}"

# ── Install AzaanBox APK ──────────────────────────────────────
echo ""
echo "Installing AzaanBox APK..."
$ADB install -r "$APK"
echo -e "${GREEN}APK installed.${NC}"

# ── Set Device Owner ──────────────────────────────────────────
echo ""
echo "Setting Device Owner..."
DPM_OUTPUT=$($ADB shell dpm set-device-owner "$ADMIN_RECEIVER" 2>&1 || true)
if echo "$DPM_OUTPUT" | grep -q "already set\|Success"; then
  echo -e "${GREEN}Device Owner set.${NC}"
else
  echo -e "${RED}Failed to set Device Owner:${NC}"
  echo "$DPM_OUTPUT"
  exit 1
fi

# ── Grant location permission ─────────────────────────────────
echo ""
echo -e "${CYAN}Granting location permission...${NC}"
$ADB shell pm grant "$PACKAGE" android.permission.ACCESS_FINE_LOCATION > /dev/null 2>&1 || true
$ADB shell pm grant "$PACKAGE" android.permission.ACCESS_COARSE_LOCATION > /dev/null 2>&1 || true
echo -e "${GREEN}Location permission granted.${NC}"

# ── Launch app ───────────────────────────────────────────────
echo ""
echo "Launching AzaanBox..."
$ADB shell am start -n "$PACKAGE/.MainActivity" > /dev/null 2>&1
echo -e "${GREEN}App launched.${NC}"

echo ""
echo -e "${GREEN}╔══════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║        Box is ready to ship!            ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════╝${NC}"
echo ""
echo "  ✓ Storage cleaned (ROM zips, tombstones, old APK cache)"
echo "  ✓ Boot animation installed"
echo "  ✓ Brightness 100%, auto-dim disabled"
echo "  ✓ AzaanBox v2.3.6 installed"
echo "  ✓ Device Owner locked (kiosk mode)"
echo "  ✓ Location permission granted"
echo "  Customer only needs to connect WiFi via the gear icon."
echo ""
