#!/bin/bash
# PlayTab App Install (macOS / Linux)
# Downloads latest APK, installs it, sets device owner, grants permissions.
# Requires ADB to be set up and a device connected (run playtab-adb.sh first).

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MANIFEST_URL="https://api.symflofi.cloud/updates/playtab/manifest.json"
UPDATES_BASE="https://api.symflofi.cloud/updates"
PKG="com.symflo.playtab"
ADMIN_RECEIVER="$PKG/.PlayTabDeviceAdminReceiver"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

info()  { echo "  $*"; }
err()   { echo "  ERROR: $*" >&2; }
die()   { err "$@"; exit 1; }

sha256_file() {
    if command -v sha256sum &>/dev/null; then
        sha256sum "$1" | cut -d' ' -f1
    elif command -v shasum &>/dev/null; then
        shasum -a 256 "$1" | cut -d' ' -f1
    else
        echo ""
    fi
}

# ---------------------------------------------------------------------------
# Check ADB + device
# ---------------------------------------------------------------------------

echo ""
echo "  ============================================"
echo "   PlayTab App Install"
echo "  ============================================"
echo ""

if command -v adb &>/dev/null; then
    ADB="adb"
elif [ -f "$SCRIPT_DIR/platform-tools/adb" ]; then
    ADB="$SCRIPT_DIR/platform-tools/adb"
else
    die "ADB not found. Run playtab-adb.sh first."
fi

ADB_STATE=$($ADB get-state 2>/dev/null || echo "unknown")
if [ "$ADB_STATE" != "device" ]; then
    die "No authorized device connected (state: $ADB_STATE).
  Make sure the tablet is plugged in and run playtab-adb.sh if needed."
fi

MODEL=$($ADB shell getprop ro.product.model 2>/dev/null | tr -d '\r')
ANDROID_VER=$($ADB shell getprop ro.build.version.release 2>/dev/null | tr -d '\r')
info "Device: $MODEL (Android $ANDROID_VER)"

# ---------------------------------------------------------------------------
# Step 1: Download latest APK
# ---------------------------------------------------------------------------

echo ""
info "Step 1: Fetching latest version..."

MANIFEST=$(curl -s --connect-timeout 10 --max-time 30 "$MANIFEST_URL" 2>/dev/null)
if [ -z "$MANIFEST" ]; then
    die "Could not fetch manifest. Check your internet connection.
  URL: $MANIFEST_URL"
fi

LATEST=""
APK_URL=""
APK_SHA=""

if command -v python3 &>/dev/null; then
    LATEST=$(echo "$MANIFEST" | python3 -c "import sys,json; print(json.load(sys.stdin)['latest'])" 2>/dev/null || true)
    APK_URL=$(echo "$MANIFEST" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['releases'][d['latest']]['apk']['url'])" 2>/dev/null || true)
    APK_SHA=$(echo "$MANIFEST" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['releases'][d['latest']]['apk']['sha256'])" 2>/dev/null || true)
elif command -v jq &>/dev/null; then
    LATEST=$(echo "$MANIFEST" | jq -r '.latest' 2>/dev/null || true)
    APK_URL=$(echo "$MANIFEST" | jq -r '.releases[.latest].apk.url' 2>/dev/null || true)
    APK_SHA=$(echo "$MANIFEST" | jq -r '.releases[.latest].apk.sha256' 2>/dev/null || true)
fi

if [ -z "$LATEST" ]; then
    if command -v perl &>/dev/null; then
        LATEST=$(echo "$MANIFEST" | perl -MJSON::PP -e '$d=decode_json(join"",<STDIN>); print $d->{latest}' 2>/dev/null || true)
        APK_URL=$(echo "$MANIFEST" | perl -MJSON::PP -e '$d=decode_json(join"",<STDIN>); print $d->{releases}{$d->{latest}}{apk}{url}' 2>/dev/null || true)
        APK_SHA=$(echo "$MANIFEST" | perl -MJSON::PP -e '$d=decode_json(join"",<STDIN>); print $d->{releases}{$d->{latest}}{apk}{sha256}' 2>/dev/null || true)
    fi
fi

if [ -z "$LATEST" ] || [ -z "$APK_URL" ]; then
    die "Could not parse manifest. Install python3 or jq and try again.
  On macOS: python3 is usually available, or: brew install jq
  On Linux: sudo apt install python3  or  sudo apt install jq"
fi

info "Latest version: v$LATEST"

APK_PATH="$SCRIPT_DIR/playtab-${LATEST}.apk"
FULL_URL="${UPDATES_BASE}/${APK_URL}"

# Check if we already have this APK with matching checksum
NEED_DOWNLOAD=true
if [ -f "$APK_PATH" ] && [ -n "$APK_SHA" ]; then
    EXISTING_SHA=$(sha256_file "$APK_PATH")
    if [ "$EXISTING_SHA" = "$APK_SHA" ]; then
        info "APK already downloaded (checksum matches)."
        NEED_DOWNLOAD=false
    fi
fi

if [ "$NEED_DOWNLOAD" = true ]; then
    info "Downloading PlayTab v${LATEST}..."
    curl -L --connect-timeout 15 --max-time 300 --progress-bar -o "$APK_PATH" "$FULL_URL"
fi

[ -f "$APK_PATH" ] || die "APK download failed."

# Verify checksum
if [ -n "$APK_SHA" ]; then
    ACTUAL_SHA=$(sha256_file "$APK_PATH")
    if [ -z "$ACTUAL_SHA" ]; then
        info "Warning: Could not verify checksum (sha256sum/shasum not found)."
    elif [ "$ACTUAL_SHA" != "$APK_SHA" ]; then
        rm -f "$APK_PATH"
        die "Checksum mismatch! APK may be corrupted.
  Expected: $APK_SHA
  Got:      $ACTUAL_SHA
  The file has been deleted. Please run the script again."
    else
        info "Checksum verified."
    fi
fi

# ---------------------------------------------------------------------------
# Step 2: Install APK
# ---------------------------------------------------------------------------

echo ""
info "Step 2: Installing PlayTab v${LATEST}..."

INSTALLED_PKG=$($ADB shell pm list packages 2>/dev/null | grep "$PKG" || true)

if [ -n "$INSTALLED_PKG" ]; then
    info "PlayTab is already installed. Attempting upgrade..."
    INSTALL_OUTPUT=$($ADB install -r "$APK_PATH" 2>&1) || true

    if echo "$INSTALL_OUTPUT" | grep -qi "INSTALL_FAILED_UPDATE_INCOMPATIBLE\|INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES\|signatures do not match"; then
        echo ""
        info "The installed version was signed with a different key."
        info "This happens when switching between debug and release builds."
        echo ""

        IS_DEVICE_OWNER=false
        if $ADB shell dumpsys device_policy 2>/dev/null | grep -q "$PKG"; then
            IS_DEVICE_OWNER=true
        fi

        if [ "$IS_DEVICE_OWNER" = true ]; then
            info "PlayTab is currently set as device owner."
            info "To reinstall, we need to:"
            info "  1. Clear device owner"
            info "  2. Uninstall the old version"
            info "  3. Install the new version"
            info "  4. Re-set device owner"
            echo ""
            read -p "  Continue? (y/N) " REPLY
            if [ "$REPLY" != "y" ] && [ "$REPLY" != "Y" ]; then
                info "Aborted."
                exit 0
            fi

            info "Clearing device owner..."
            $ADB shell dpm remove-active-admin "$ADMIN_RECEIVER" 2>/dev/null || true
        fi

        info "Uninstalling old version..."
        $ADB uninstall "$PKG" 2>/dev/null || true

        info "Installing PlayTab v${LATEST} (fresh install)..."
        INSTALL_OUTPUT=$($ADB install "$APK_PATH" 2>&1)
        if [ $? -ne 0 ]; then
            err "Installation failed:"
            echo "  $INSTALL_OUTPUT"
            exit 1
        fi
    elif echo "$INSTALL_OUTPUT" | grep -qi "Success"; then
        : # Upgrade succeeded
    else
        err "Installation failed:"
        echo "  $INSTALL_OUTPUT"
        echo ""
        info "Troubleshooting:"
        info "  - Check if the tablet has enough storage"
        info "  - Try: adb uninstall $PKG  then run this script again"
        exit 1
    fi
else
    INSTALL_OUTPUT=$($ADB install "$APK_PATH" 2>&1)
    if [ $? -ne 0 ]; then
        err "Installation failed:"
        echo "  $INSTALL_OUTPUT"
        exit 1
    fi
fi
info "Installed successfully."

# ---------------------------------------------------------------------------
# Step 3: Set device owner
# ---------------------------------------------------------------------------

echo ""
info "Step 3: Setting up device owner..."

if $ADB shell dumpsys device_policy 2>/dev/null | grep -q "$PKG"; then
    info "PlayTab is already device owner. Skipping."
else
    ACCOUNT_OUTPUT=$($ADB shell dumpsys account 2>/dev/null || true)
    ACCOUNT_COUNT=$(echo "$ACCOUNT_OUTPUT" | grep -c "Account {name=" 2>/dev/null || echo "0")

    if [ "$ACCOUNT_COUNT" -gt 0 ] 2>/dev/null; then
        echo ""
        info "WARNING: The tablet has $ACCOUNT_COUNT user account(s) that will"
        info "prevent device owner setup."
        echo ""
        info "Please remove all accounts now:"
        info "  Settings > Accounts > Remove each account"
        echo ""
        info "After removing accounts, press Enter to continue."
        read -p "  Press Enter after removing all accounts..."
    fi

    ERR_FILE=$(mktemp /tmp/playtab_install_XXXXXX 2>/dev/null || echo "/tmp/playtab_install_err.txt")
    if $ADB shell dpm set-device-owner "$ADMIN_RECEIVER" 2>"$ERR_FILE"; then
        info "Device owner set."
    else
        echo ""
        err "Could not set device owner."
        echo ""
        if [ -f "$ERR_FILE" ]; then
            cat "$ERR_FILE"
        fi
        echo ""
        info "Common fixes:"
        info "  - Remove ALL Google/user accounts from the tablet"
        info "    (Settings > Accounts > Remove each account)"
        info "  - Make sure no other app is already set as device owner"
        info "    Check: adb shell dumpsys device_policy"
        info "  - On some tablets, you also need to remove the SIM card"
        info "  - Factory reset the tablet if nothing else works"
        echo ""
        rm -f "$ERR_FILE"
        exit 1
    fi
    rm -f "$ERR_FILE"
fi

# ---------------------------------------------------------------------------
# Step 4: Grant overlay permission
# ---------------------------------------------------------------------------

echo ""
info "Step 4: Granting overlay permission..."
$ADB shell appops set "$PKG" SYSTEM_ALERT_WINDOW allow
info "Done."

# ---------------------------------------------------------------------------
# Step 5: Launch the app
# ---------------------------------------------------------------------------

echo ""
info "Step 5: Launching PlayTab..."
$ADB shell am start -n "$PKG/.MainActivity" 2>/dev/null || true

echo ""
echo "  ============================================"
echo "   SUCCESS! PlayTab v${LATEST} is ready."
echo "  ============================================"
echo ""
info "Next steps:"
info "  1. PlayTab should now be open on the tablet"
info "  2. Go to Admin Panel (PIN: 1234)"
info "  3. Tap \"Enable Kiosk Mode\""
info "  4. Unplug USB — you're done!"
echo ""
