#!/system/bin/sh
# UltraOpt • Ultimate v6.00
# customize.sh (SAFE installer)
# - Auto-select 32/64-bit payload (32BIT.tar / 64BIT.tar)
# - No early "optimizations" during install (safety first)
# - Sets sane permissions for executables only

SKIPMOUNT=false
PROPFILE=true
POSTFSDATA=true
LATESTARTSERVICE=true

# ---------------- UI helpers ----------------
print_separator(){ ui_print " "; ui_print "----------------------------------------"; }
print_header(){
  ui_print " "
  ui_print "========================================"
  ui_print "       UltraOpt • Ultimate v6.00 ✅"
  ui_print "       Author: TosikV2 • Magisk"
  ui_print "========================================"
  ui_print " "
}
ok(){ ui_print "✅ $1"; }
warn(){ ui_print "⚠️  $1"; }
err(){ ui_print "❌ $1"; }
info(){ ui_print "ℹ️  $1"; }

progress_step(){
  # Usage: progress_step "1/4" "Message"
  ui_print " "
  ui_print "[ $1 ] $2"
  ui_print "----------------------------------------"
}

# ---------------- Start ----------------
print_header
sleep 2

MODPATH="${MODPATH:-${0%/*}}"
TAR64="$MODPATH/64BIT.tar"
TAR32="$MODPATH/32BIT.tar"

progress_step "1/4" "Device & compatibility checks"
sleep 1
API="$(getprop ro.build.version.sdk 2>/dev/null)"
ANDROID="$(getprop ro.build.version.release 2>/dev/null)"
DEVICE="$(getprop ro.product.model 2>/dev/null)"
ARCH_ABI="$(getprop ro.product.cpu.abi 2>/dev/null)"
ABILIST64="$(getprop ro.product.cpu.abilist64 2>/dev/null)"

ui_print "  • Device:  $DEVICE"
ui_print "  • Android: $ANDROID (API $API)"
ui_print "  • ABI:     $ARCH_ABI"

ui_print " "
ui_print "🧪 Compatibility"
print_separator

# Android gate (as requested):
# - Android 8.x and below (API <= 27): abort
# - Android 9-10 (API 28-29): warn but continue
# - Android 11-15 (API 30-34): recommended
# - Android 16 (API 35): warn but continue
case "$API" in
  ''|*[!0-9]*)
    warn "Can't read Android API level — proceeding carefully"
    ;;
  [0-9]|1[0-9]|2[0-7])
    err "Android 8.x and below is NOT supported."
    err "Reason: missing modern APIs / inconsistent behavior."
    err "Detected: Android $ANDROID (API $API)"
    abort
    ;;
  28|29)
    warn "Android $ANDROID detected (API $API) — potentially outdated."
    warn "Install will continue, but you may see minor issues."
    sleep 1
    ;;
  30|31|32|33|34)
    ok "Android $ANDROID detected (API $API) — fully supported."
    ;;
  35)
    warn "Android 16 detected (API 35) — new platform."
    warn "Install will continue, but compatibility issues are possible."
    sleep 1
    ;;
  *)
    warn "Android API $API detected — unknown/new."
    warn "Install will continue carefully."
    sleep 1
    ;;
esac

# ---------------- ABI detect + extract ----------------
ui_print " "
progress_step "2/4" "Installing correct binaries"
sleep 3
# Detect userspace bitness (not only CPU)
is64=0
[ -n "$ABILIST64" ] && is64=1
[ -x /system/bin/app_process64 ] && is64=1

# Detect obvious 32-bit-only
is32=0
echo "$ARCH_ABI" | grep -qE 'armeabi|armeabi-v7a' && is32=1

# If detection is weird, abort (as you asked)
if [ "$is64" = "1" ] && [ "$is32" = "1" ]; then
  warn "Mixed ABI reported (32+64). Using 64-bit payload."
  is32=0
fi

if [ "$is64" = "1" ]; then
  [ -f "$TAR64" ] || { err "64BIT.tar not found in module"; abort; }
  info "Detected: 64-bit ✅"
  tar -xf "$TAR64" -C "$MODPATH" 2>/dev/null || { err "Failed to extract 64BIT.tar"; abort; }
  ok "64-bit payload extracted"
elif [ "$is32" = "1" ]; then
  [ -f "$TAR32" ] || { err "32BIT.tar not found in module"; abort; }
  info "Detected: 32-bit ✅"
  tar -xf "$TAR32" -C "$MODPATH" 2>/dev/null || { err "Failed to extract 32BIT.tar"; abort; }
  ok "32-bit payload extracted"
else
  err "Unknown/unsupported CPU ABI. Only 32-bit ARM and 64-bit ARM are supported."
  err "ABI=$ARCH_ABI  abilist64=$ABILIST64"
  abort
fi

# Optional: remove payload tar to save space
rm -f "$TAR64" "$TAR32" 2>/dev/null

# ---------------- Permissions (executables only) ----------------
ui_print " "
progress_step "3/4" "Setting permissions"
sleep 2.5
# Binaries
if [ -d "$MODPATH/system/bin" ]; then
  chmod 0755 "$MODPATH/system/bin/"* 2>/dev/null
  ok "system/bin/* -> 755"
else
  warn "system/bin not found (payload structure issue?)"
fi

# Scripts
for f in "$MODPATH/service.sh" "$MODPATH/post-fs-data.sh" "$MODPATH/uninstall.sh" "$MODPATH/customize.sh"; do
  [ -f "$f" ] && chmod 0755 "$f" 2>/dev/null
done
ok "scripts -> 755"

# Configs should NOT be executable
[ -f "$MODPATH/mod.cfg" ] && chmod 0600 "$MODPATH/mod.cfg" 2>/dev/null

sleep 2
ui_print " "
ui_print " "
ui_print "╔══════════════════════════════════════╗"
ui_print "║           INSTALLATION COMPLETE           ║"
ui_print "╚══════════════════════════════════════╝"
ui_print " "
sleep 3
ui_print "Available Commands:"
print_separator
ui_print ""
ui_print " 💤 hibernation    - Smart CPU governor control (by default it runs in the background)"
ui_print "  ultraopt    - Module configuration"
ui_print ""
ui_print "  Supports: 1) Interactive menu 2) CLI usage"
ui_print ""
ui_print " ⚙️ CLI examples: "
ui_print "su -c ultraopt -ram"
ui_print "su -c ultraopt -clean"
ui_print "su -c ultraopt -dex"
ui_print "su -c ultraopt -bg"
ui_print "su -c ultraopt -tcp"
ui_print "su -c ultraopt -h"
sleep 1
ui_print "Configuration:"
ui_print "  /data/adb/modules/UltrOpt/mod.cfg"
ui_print " "
sleep 1
ui_print "Features:"
ui_print "  • Smart governor switching (screen on/off)"
ui_print "  • Aggressive logging reduction"
ui_print "  • Network optimization (TCP, buffers)"
ui_print "  • Safe and reversible"
ui_print " "
sleep 4
ui_print " "
ui_print "✅ Installation finished!"
ui_print "🧩 Config: /data/adb/modules/UltrOpt/mod.cfg"
ui_print " "
sleep 2
ui_print "Telegram: @opensourcemagiskmodule"
sleep 1
am start -a android.intent.action.VIEW -d "https://t.me/opensourcemagiskmodule" >/dev/null 2>&1
ui_print "🔁 Reboot recommended."
