#!/system/bin/sh
CPU_GOV="/sys/devices/system/cpu/cpu0/cpufreq"
DEST_DIR="/data/adb/modules/RaiRin-AI/cortex/cpu"
DEST_FILE="$DEST_DIR/default-gov.txt"
DND="$DEST_DIR/dnd.txt"
normal="Applying Balance Mode"
mtk="Mediatek Balance Applied"
snap="Snapdragon Balance Applied"
uni="UniSOC Balance Applied"
exy="Exynos Balance Applied"
tensor="Tensor Balance Applied"
SWAP_FILE="/data/local/tmp/swappiness_backup"
SWAP_PATH="/proc/sys/vm/swappiness"
safe_toast() {
  if [ -x /system/bin/am ]; then
    am start -a android.intent.action.MAIN -e toasttext "$1" -n bellavita.toast/.MainActivity 2>/dev/null &
  fi
}

apply() {
    local value="$1"
    local file="$2"
    [ -f "$file" ] || return 1
    chmod 0666 "$file" 2>/dev/null
    echo "$value" > "$file" 2>/dev/null
    chmod 0444 "$file" 2>/dev/null
}

max() {
    [ -f "$1" ] || return 1
    tr ' ' '\n' <"$1" | grep -E '^[0-9]+$' | sort -nr | head -n 1
}

min() {
    [ -f "$1" ] || return 1
    tr ' ' '\n' <"$1" | grep -E '^[0-9]+$' | sort -n | head -n 1
}

mid() {
    [ -f "$1" ] || return 1
    local total_opp mid_opp
    total_opp=$(tr ' ' '\n' <"$1" | grep -E '^[0-9]+$' | wc -l)
    [ "$total_opp" -eq 0 ] && return 1
    mid_opp=$(((total_opp + 1) / 2))
    tr ' ' '\n' <"$1" | grep -E '^[0-9]+$' | sort -nr | head -n "$mid_opp" | tail -n 1
}
safe_toast() {
  if [ -x /system/bin/am ]; then
    am start -a android.intent.action.MAIN -e toasttext "$1" -n bellavita.toast/.MainActivity 2>/dev/null &
  fi
}
cpu_free() {
    for path in /sys/devices/system/cpu/*/cpufreq; do
        if [ -f "$path/scaling_available_frequencies" ]; then
            cpu_maxfreq=$(max "$path/scaling_available_frequencies")
            cpu_minfreq=$(min "$path/scaling_available_frequencies")
        else
            cpu_maxfreq=$(<"$path/cpuinfo_max_freq")
            cpu_minfreq=$(<"$path/cpuinfo_min_freq")
        fi
        apply "$cpu_maxfreq" "$path/scaling_max_freq"
        apply "$cpu_minfreq" "$path/scaling_min_freq"
    done
}
devfreq_max() {
    [ -f "$1/available_frequencies" ] || return 1
    max_freq=$(max "$1/available_frequencies")
    apply "$max_freq" "$1/max_freq"
    apply "$max_freq" "$1/min_freq"
}

devfreq_mid() {
    [ -f "$1/available_frequencies" ] || return 1
    max_freq=$(mid "$1/available_frequencies")
    mid_freq=$(min "$1/available_frequencies")
    apply "$max_freq" "$1/max_freq"
    apply "$mid_freq" "$1/min_freq"
}

devfreq_free() {
    [ -f "$1/available_frequencies" ] || return 1
    max_freq=$(max "$1/available_frequencies")
    min_freq=$(min "$1/available_frequencies")
    apply "$max_freq" "$1/max_freq"
    apply "$min_freq" "$1/min_freq"
}
devfreq_min() {
    [ -f "$1/available_frequencies" ] || return 1
    max_freq=$(max "$1/available_frequencies")
    mid_freq=$(mid "$1/available_frequencies")
    apply "$min_freq" "$1/max_freq"
    apply "$min_freq" "$1/min_freq"
}

set_governor() {
    for gov in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor \
                   /sys/devices/system/cpu/cpufreq/policy*/scaling_governor; do
        [ -f "$gov" ] && apply "$1" "$gov"
    done
}


# === Performance Utilities ===
ppm_mid() {
    cluster=-1
    for path in /sys/devices/system/cpu/cpufreq/policy*; do
        ((cluster++))
        if [ -f "$path/scaling_available_frequencies" ]; then
            cpu_maxfreq=$(mid "$path/scaling_available_frequencies")
        else
            cpu_maxfreq=$(<"$path/cpuinfo_max_freq")
        fi
        apply "$cluster $cpu_maxfreq" /proc/ppm/policy/hard_userlimit_max_cpu_freq
        apply "$cluster $cpu_maxfreq" /proc/ppm/policy/hard_userlimit_min_cpu_freq
    done
}
cpu_mid() {
    for path in /sys/devices/system/cpu/*/cpufreq; do
        if [ -f "$path/scaling_available_frequencies" ]; then
            cpu_maxfreq=$(mid "$path/scaling_available_frequencies")
        else
            cpu_maxfreq=$(<"$path/cpuinfo_max_freq")
        fi
        apply "$cpu_maxfreq" "$path/scaling_max_freq"
        apply "$cpu_maxfreq" "$path/scaling_min_freq"
    done
}

# === Balance ===
mtk_balance() {
    safe_toast "$mtk"

    # --- daftar apply standar ---
    APPLY_LIST="
0 /proc/cpufreq/cpufreq_cci_mode
1 /proc/cpufreq/cpufreq_power_mode
0 /proc/gpufreq/gpufreq_opp_freq
-1 /proc/gpufreqv2/fix_target_opp_index
1 /sys/devices/system/cpu/eas/enable
0 /proc/perfmgr/syslimiter/syslimiter_force_disable
stop 0 /proc/mtk_batoc_throttling/battery_oc_protect_stop
stop 0 /proc/pbm/pbm_stop
1 /sys/kernel/eara_thermal/enable
-1 /sys/devices/platform/10012000.dvfsrc/helio-dvfsrc/dvfsrc_req_ddr_opp
-1 /sys/kernel/helio-dvfsrc/dvfsrc_force_vcore_dvfs_opp
userspace /sys/class/devfreq/mtk-dvfsrc-devfreq/governor
userspace /sys/devices/platform/soc/1c00f000.dvfsrc/mtk-dvfsrc-devfreq/devfreq/mtk-dvfsrc-devfreq/governor
"

    # --- eksekusi apply list ---
    while read -r value file; do
        [ -n "$file" ] && apply "$value" "$file"
    done <<EOF
$APPLY_LIST
EOF

    # --- Power policy GPU ---
    echo "coarse_demand" > /sys/class/devfreq/13000000.mali/device/power_policy

    # --- PPM Settings ---
    if [ -f /proc/ppm/policy_status ]; then
        grep -E 'FORCE_LIMIT|PWR_THRO|THERMAL|USER_LIMIT' /proc/ppm/policy_status \
            | awk -F'[][]' '{print $2}' \
            | while read -r idx; do
                apply "$idx 1" "/proc/ppm/policy_status"
              done

        grep -E 'SYS_BOOST' /proc/ppm/policy_status \
            | awk -F'[][]' '{print $2}' \
            | while read -r dx; do
                apply "$dx 0" "/proc/ppm/policy_status"
              done
    fi

    # --- GPU Power limiter (aktifkan limiter) ---
    if [ -f "/proc/gpufreq/gpufreq_power_limited" ]; then
        for setting in ignore_batt_oc ignore_batt_percent ignore_low_batt ignore_thermal_protect ignore_pbm_limited; do
            apply "$setting 0" /proc/gpufreq/gpufreq_power_limited
        done
    fi

    # --- DDR freq: tengah ---
    devfreq_mid
}
snap_balance() {
safe_toast "$snap"
    # Qualcomm CPU Bus and DRAM frequencies
    for path in /sys/class/devfreq/*cpu-ddr-latfloor*; do
        apply "compute" $path/governor
    done &

    for path in /sys/class/devfreq/*cpu*-lat; do
        apply "mem_latency" $path/governor
    done &

    for path in /sys/class/devfreq/*cpu-cpu-ddr-bw; do
        apply "bw_hwmon" $path/governor
    done &

    for path in /sys/class/devfreq/*cpu-cpu-llcc-bw; do
        apply "bw_hwmon" $path/governor
    done &

    if [ -d /sys/devices/system/cpu/bus_dcvs/LLCC ]; then
        max_freq=$(cat /sys/devices/system/cpu/bus_dcvs/LLCC/available_frequencies | tr ' ' '\n' | sort -nr | head -n 1)
        min_freq=$(cat /sys/devices/system/cpu/bus_dcvs/LLCC/available_frequencies | tr ' ' '\n' | sort -n | head -n 1)
        for path in /sys/devices/system/cpu/bus_dcvs/LLCC/*/max_freq; do
            apply $max_freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/LLCC/*/min_freq; do
            apply $min_freq $path
        done &
    fi

    if [ -d /sys/devices/system/cpu/bus_dcvs/L3 ]; then
        max_freq=$(cat /sys/devices/system/cpu/bus_dcvs/L3/available_frequencies | tr ' ' '\n' | sort -nr | head -n 1)
        min_freq=$(cat /sys/devices/system/cpu/bus_dcvs/L3/available_frequencies | tr ' ' '\n' | sort -n | head -n 1)
        for path in /sys/devices/system/cpu/bus_dcvs/L3/*/max_freq; do
            apply $max_freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/L3/*/min_freq; do
            apply $min_freq $path
        done &
    fi

    if [ -d /sys/devices/system/cpu/bus_dcvs/DDR ]; then
        max_freq=$(cat /sys/devices/system/cpu/bus_dcvs/DDR/available_frequencies | tr ' ' '\n' | sort -nr | head -n 1)
        min_freq=$(cat /sys/devices/system/cpu/bus_dcvs/DDR/available_frequencies | tr ' ' '\n' | sort -n | head -n 1)
        for path in /sys/devices/system/cpu/bus_dcvs/DDR/*/max_freq; do
            apply $max_freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/DDR/*/min_freq; do
            apply $min_freq $path
        done &
    fi

    if [ -d /sys/devices/system/cpu/bus_dcvs/DDRQOS ]; then
        max_freq=$(cat /sys/devices/system/cpu/bus_dcvs/DDRQOS/available_frequencies | tr ' ' '\n' | sort -nr | head -n 1)
        min_freq=$(cat /sys/devices/system/cpu/bus_dcvs/DDRQOS/available_frequencies | tr ' ' '\n' | sort -n | head -n 1)
        for path in /sys/devices/system/cpu/bus_dcvs/DDRQOS/*/max_freq; do
            apply $max_freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/DDRQOS/*/min_freq; do
            apply $min_freq $path
        done &
    fi

    # GPU Frequency
    gpu_path="/sys/class/kgsl/kgsl-3d0/devfreq"

    if [ -d $gpu_path ]; then
        max_freq=$(cat $gpu_path/available_frequencies | tr ' ' '\n' | sort -nr | head -n 1)
        min_freq=$(cat $gpu_path/available_frequencies | tr ' ' '\n' | sort -n | head -n 2)
        apply $min_freq $gpu_path/min_freq
        apply $max_freq $gpu_path/max_freq
    fi

    # GPU Bus
    for path in /sys/class/devfreq/*gpubw*; do
        apply "bw_vbif" $path/governor
    done &

    # Adreno Boost
    apply 1 /sys/class/kgsl/kgsl-3d0/devfreq/adrenoboost
    
}

exynos_balance() {
    safe_toast "$exy"

    # --- GPU Frequency ---
    gpu_path="/sys/kernel/gpu"
    if [ -d "$gpu_path" ]; then
        max_freq=$(max "$gpu_path/gpu_available_frequencies")
        min_freq=$(min "$gpu_path/gpu_available_frequencies")
        APPLY_LIST="
$max_freq $gpu_path/gpu_max_clock
$min_freq $gpu_path/gpu_min_clock
"
    fi

    # --- Mali sysfs policy ---
    mali_sysfs=$(find /sys/devices/platform/ -iname "*.mali" -print -quit 2>/dev/null)
    APPLY_LIST="$APPLY_LIST
coarse_demand $mali_sysfs/power_policy
"

    # eksekusi apply list
    while read -r value file; do
        [ -n "$file" ] && apply "$value" "$file"
    done <<EOF
$APPLY_LIST
EOF

    # --- DRAM frequency ---
    if [ "$DEVICE_MITIGATION" -eq 0 ]; then
        for path in /sys/class/devfreq/*devfreq_mif*; do
            devfreq_free "$path"
        done &
    fi
}

unisoc_balance() {
    safe_toast "$uni"
    # GPU Frequency
    gpu_path=$(find /sys/class/devfreq/ -type d -iname "*.gpu" -print -quit 2>/dev/null)
    [ -n "$gpu_path" ] && devfreq_unlock "$gpu_path"
}

tensor_balance() {
    safe_toast "$tensor"

    # --- GPU Frequency ---
    gpu_path=$(find /sys/devices/platform/ -type d -iname "*.mali" -print -quit 2>/dev/null)
    if [ -n "$gpu_path" ]; then
        max_freq=$(max "$gpu_path/available_frequencies")
        min_freq=$(min "$gpu_path/available_frequencies")
        APPLY_LIST="
$max_freq $gpu_path/scaling_max_freq
$min_freq $gpu_path/scaling_min_freq
"
        while read -r value file; do
            [ -n "$file" ] && apply "$value" "$file"
        done <<EOF
$APPLY_LIST
EOF
    fi

    # --- DRAM frequency ---
    if [ "$DEVICE_MITIGATION" -eq 0 ]; then
        for path in /sys/class/devfreq/*devfreq_mif*; do
            devfreq_free "$path"
        done &
    fi
}
gms() {
    DND_FILE="/data/adb/modules/thunderclash/dnd"

    # Pastikan file ada
    if [ ! -f "$DND_FILE" ]; then
        echo "File DND tidak ditemukan, asumsi 0 (nonaktif)"
        DND=0
    else
        DND=$(cat "$DND_FILE" 2>/dev/null)
    fi

    # Jika DND = 1 → disable GMS, jika 0 → enable GMS
    if [ "$DND" = "1" ]; then
        cmd package disable-user com.google.android.gms 2>/dev/null
        echo "DND aktif (1) → GMS dinonaktifkan"
    else
        cmd package enable com.google.android.gms 2>/dev/null
        echo "DND nonaktif (0) → GMS diaktifkan"
    fi
}
balanced_profile() {
    save_gov() {
        if [ -f "$DEST_FILE" ]; then
            value=$(cat "$DEST_FILE")
            if [ -z "$value" ] || [ "$value" = "performance" ]; then
                echo "schedutil"
            else
                echo "$value"
            fi
        else
            echo "schedutil"
        fi
    }

    # Load default cpu governor
    default_gov=$(save_gov)

    
    

    # --- Perf device power level ---
    for pl in /sys/devices/system/cpu/perf; do
        apply 0 "$pl/gpu_pmu_enable"
        apply 0 "$pl/fuel_gauge_enable"
        apply 0 "$pl/enable"
        apply 1 "$pl/charger_enable"
    done

    # --- Restore CPU governor ---
    set_governor "$default_gov"

    # --- Restore CPU cluster freqs ---
    if [ -d /proc/ppm ]; then
        cluster=0
        for path in /sys/devices/system/cpu/cpufreq/policy*; do
            [ -f "$path/cpuinfo_max_freq" ] || continue
            [ -f "$path/cpuinfo_min_freq" ] || continue
            read -r cpu_maxfreq < "$path/cpuinfo_max_freq"
            read -r cpu_minfreq < "$path/cpuinfo_min_freq"
            apply "$cluster $cpu_maxfreq" "/proc/ppm/policy/hard_userlimit_max_cpu_freq"
            apply "$cluster $cpu_minfreq" "/proc/ppm/policy/hard_userlimit_min_cpu_freq"
            cluster=$((cluster + 1))
        done
    fi

    # --- Let kernel manage CPU scaling ---
    cpu_free

    # --- Schedtune settings ---
    for path in /dev/stune/*; do
        apply 0 "$path/schedtune.boost"
        apply 0 "$path/schedtune.sched_boost_enabled"
        apply 0 "$path/schedtune.prefer_idle"
        apply 0 "$path/schedtune.colocate"
    done

    # --- CPU Core control Boost ---
    for cpucore in /sys/devices/system/cpu/cpu*; do
        apply 0 "$cpucore/core_ctl/enable"
        apply 0 "$cpucore/core_ctl/core_ctl_boost"
    done

    # --- Battery saver ---
    if [ -f /sys/module/battery_saver/parameters/enabled ]; then
        if /vendor/bin/grep -qo '[0-9]\+' /sys/module/battery_saver/parameters/enabled; then
            apply 0 /sys/module/battery_saver/parameters/enabled
        else
            apply N /sys/module/battery_saver/parameters/enabled
        fi
    fi
    
    
    

    # --- SOC-specific balance mode ---
    case "$(cat /data/local/tmp/thunder_default/soc)" in
        1) mtk_balance ;;
        2) snap_balance ;;
        3) exynos_balance ;;
        4) unisoc_balance ;;
        5) tensor_balance ;;
    esac
}
# Activating Balance
#safe_toast "$normal"
cmd notification set_dnd off
settings put global zen_mode 0
balanced_profile
cmd display set-user-disabled-hdr-types
echo "normal" > "/data/adb/modules/RaiRin-AI/cortex/thunderclash/current_mode"
exit 0


