#!/system/bin/sh
# UltraOpt post-fs-data.sh (reworked, safe-first)
# - Early sysfs/proc tuning: I/O + VM + LMK (no CPU/GPU boost)
# - No settings/pm/force-stop here (too early)
# - Everything is guarded by existence + writable checks

MODNAME="UltrOpt"
CFG="/data/adb/modules/${MODNAME}/mod.cfg"
LOG="/data/local/tmp/UltraOpt_postfs.log"
LOG_TAG="UltrOpt/post-fs-data"
log_msg(){ echo "$LOG_TAG: $1"; }

log(){ echo "[UltraOpt][post-fs-data][$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG" 2>/dev/null; }

w(){ [ -w "$1" ] && echo "$2" > "$1" 2>/dev/null && return 0; return 1; }

# --- I/O scheduler + queue tuning (safe for flash) ---
pick_sched(){
  # prefer simple schedulers for flash
  local sfile="$1"
  local want
  for want in mq-deadline deadline none noop kyber bfq; do
    grep -q "$want" "$sfile" 2>/dev/null && { echo "$want"; return 0; }
  done
  return 1
}

tune_block(){
  local dev="$1"
  local sch="/sys/block/$dev/queue/scheduler"
  local ra="/sys/block/$dev/queue/read_ahead_kb"
  local ios="/sys/block/$dev/queue/iostats"

  if [ -f "$sch" ] && [ -w "$sch" ]; then
    sel="$(pick_sched "$sch")"
    [ -n "$sel" ] && echo "$sel" > "$sch" 2>/dev/null && log "I/O scheduler $dev -> $sel"
  fi

  if [ -f "$ra" ] && [ -w "$ra" ]; then
    cur="$(cat "$ra" 2>/dev/null)"
    [ -n "$cur" ] && [ "$cur" -lt 128 ] && echo 128 > "$ra" 2>/dev/null && log "read_ahead_kb $dev: $cur -> 128"
  fi

  # reduce overhead
  [ -f "$ios" ] && [ -w "$ios" ] && echo 0 > "$ios" 2>/dev/null
}

for d in /sys/block/*; do
  dev="$(basename "$d")"
  # skip loop/ram devices
  echo "$dev" | grep -qE '^(loop|ram)' && continue
  tune_block "$dev"
done

# --- VM tuning (conservative) ---
# Dirty ratios to smooth writeback spikes
w /proc/sys/vm/dirty_background_ratio 5 && log "vm.dirty_background_ratio=5"
w /proc/sys/vm/dirty_ratio 10 && log "vm.dirty_ratio=10"
# Keep default-ish cache pressure
w /proc/sys/vm/vfs_cache_pressure 100
# Swappiness: if zram/swap exists -> a bit higher
if grep -qE 'zram|swap' /proc/swaps 2>/dev/null; then
  w /proc/sys/vm/swappiness 80 && log "vm.swappiness=80 (swap present)"
else
  w /proc/sys/vm/swappiness 60 && log "vm.swappiness=60"
fi

# --- LMK (only old kernel driver; do NOT touch lmkd/PSI) ---
LMK="/sys/module/lowmemorykiller/parameters/minfree"
if [ -f "$LMK" ] && [ -w "$LMK" ]; then
  mem_kb="$(grep -m1 '^MemTotal:' /proc/meminfo 2>/dev/null | awk '{print $2}')"
  # Choose moderate presets by RAM size
  # values are pages (4KB). Conservative to avoid killing apps too early.
  if [ -n "$mem_kb" ]; then
    if [ "$mem_kb" -lt 4096000 ]; then
      echo "8192,10240,12288,14336,16384,20480" > "$LMK" 2>/dev/null && log "LMK minfree preset for <4GB"
    elif [ "$mem_kb" -lt 8192000 ]; then
      echo "10240,12288,14336,16384,20480,24576" > "$LMK" 2>/dev/null && log "LMK minfree preset for 4-8GB"
    else
      # High-RAM devices: usually better to leave stock
      log "LMK present, but RAM is high; leaving stock minfree"
    fi
  fi
fi


log_msg "Disabling telemetry and logging..."
resetprop -n debug.performance.tuning 0
resetprop -n persist.sys.dalvik.vm.lib.2 libart.so
resetprop -n dalvik.vm.dexopt.secondary true
resetprop -n pm.dexopt.install everything

log_msg "Setting optimal TCP congestion control..."
AVAILABLE_CC="$(cat /proc/sys/net/ipv4/tcp_available_congestion_control 2>/dev/null)"
CURRENT_CC="$(cat /proc/sys/net/ipv4/tcp_congestion_control 2>/dev/null)"
log_msg "Available: $AVAILABLE_CC"
log_msg "Current: $CURRENT_CC"

PRIORITY_LIST="bbr3 bbr2 bbr cubic westwood reno bic"
SELECTED_CC=""

for cc in $PRIORITY_LIST; do
    if echo " $AVAILABLE_CC " | grep -q " $cc "; then
        SELECTED_CC="$cc"
        log_msg "Found in priority list: $SELECTED_CC"
        break
    fi
done

if [ -z "$SELECTED_CC" ]; then
    log_msg "No priority CC available, keeping current: $CURRENT_CC"
else
    if [ "$CURRENT_CC" != "$SELECTED_CC" ]; then
        echo "$SELECTED_CC" > /proc/sys/net/ipv4/tcp_congestion_control 2>/dev/null
        
        NEW_CC="$(cat /proc/sys/net/ipv4/tcp_congestion_control 2>/dev/null)"
        if [ "$NEW_CC" = "$SELECTED_CC" ]; then
            log_msg "Successfully set TCP CC: $CURRENT_CC → $NEW_CC"
        elif [ -n "$NEW_CC" ]; then
            log_msg "Failed to set $SELECTED_CC, got: $NEW_CC (keeping it)"
        else
            log_msg "Failed to set TCP CC, keeping current: $CURRENT_CC"
        fi
    else
        log_msg "TCP CC already optimal: $CURRENT_CC"
    fi
fi

FINAL_CC="$(cat /proc/sys/net/ipv4/tcp_congestion_control 2>/dev/null || echo "$CURRENT_CC")"

log_msg "Disabling kernel tracing..."
for debugfs in /sys/kernel/debug/*; do
  [ -e "$debugfs/tracing/tracing_on" ] && echo "0" > "$debugfs/tracing/tracing_on" 2>/dev/null
  [ -e "$debugfs/tracing/events/enable" ] && echo "0" > "$debugfs/tracing/events/enable" 2>/dev/null
done

for t in /sys/kernel/debug/tracing/tracing_on /sys/kernel/tracing/tracing_on; do
  [ -w "$t" ] && echo 0 > "$t" 2>/dev/null && log "tracing_off: $t"
done

log_msg "Cleaning event logs..."
resetprop -n persist.logd.security_events false
resetprop -n persist.logd.auditd.enabled false
resetprop -n persist.logd.kernel false

resetprop -n debug.hwui.profile false
resetprop -n debug.hwui.overdraw false
resetprop -n debug.layout false
resetprop -n debug.performance.tuning 0

log_msg "Finalizing optimizations..."
log_msg "Final TCP CC: $FINAL_CC"
exit 0
