#!/system/bin/sh
CPU_GOV="/sys/devices/system/cpu/cpu0/cpufreq"
DEST_DIR="/data/local/tmp/thunder_default"
DEST_FILE="$DEST_DIR/governor_default.txt"
DND="$DEST_DIR/dnd.txt"
normal="Applying Performance Mode"
mtk="Mediatek Performance Applied"
snap="Snapdragon Performance Applied"
uni="UniSOC Performance Applied"
exy="Exynos Performance Applied"
tensor="Tensor Performance Applied"
TMP_ICON="/data/local/tmp/rairin.webp"
TMP="/data/local/tmp/RaiRin-AI"
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
}
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=$(max "$1/available_frequencies")
    mid_freq=$(mid "$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"
}
qcom_cpudcvs_max() {
    [ -f "$1/available_frequencies" ] || return 1
    freq=$(max "$1/available_frequencies")
    apply "$freq" "$1/hw_max_freq"
    apply "$freq" "$1/hw_min_freq"
}

qcom_cpudcvs_mid() {
    [ -f "$1/available_frequencies" ] || return 1
    max_freq=$(max "$1/available_frequencies")
    mid_freq=$(mid "$1/available_frequencies")
    apply "$max_freq" "$1/hw_max_freq"
    apply "$mid_freq" "$1/hw_min_freq"
}

qcom_cpudcvs_free() {
    [ -f "$1/available_frequencies" ] || return 1
    max_freq=$(max "$1/available_frequencies")
    min_freq=$(min "$1/available_frequencies")
    apply "$max_freq" "$1/hw_max_freq"
    apply "$min_freq" "$1/hw_min_freq"
}

qcom_cpudcvs_min() {
    [ -f "$1/available_frequencies" ] || return 1
    freq=$(min "$1/available_frequencies")
    apply "$freq" "$1/hw_min_freq"
    apply "$freq" "$1/hw_max_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_max() {
    cluster=-1
    for path in /sys/devices/system/cpu/cpufreq/policy*; do
        ((cluster++))
        if [ -f "$path/scaling_available_frequencies" ]; then
            cpu_maxfreq=$(max "$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_max() {
    for path in /sys/devices/system/cpu/*/cpufreq; do
        if [ -f "$path/scaling_available_frequencies" ]; then
            cpu_maxfreq=$(max "$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
}
mediatek_performance() {
    safe_toast "$mtk"

    ########################
    # PPM Settings
    ########################
    if [ -d /proc/ppm ] && [ -f /proc/ppm/policy_status ]; then
        for idx in $(/vendor/bin/grep -E 'FORCE_LIMIT|PWR_THRO|THERMAL|USER_LIMIT' /proc/ppm/policy_status | /system/bin/awk -F'[][]' '{print $2}'); do
            apply "$idx 0" "/proc/ppm/policy_status"
        done
        for dx in $(/vendor/bin/grep -E 'SYS_BOOST' /proc/ppm/policy_status | /system/bin/awk -F'[][]' '{print $2}'); do
            apply "$dx 1" "/proc/ppm/policy_status"
        done
    fi

    ########################
    # CPU Power Mode
    ########################
    apply "1" "/proc/cpufreq/cpufreq_cci_mode"
    apply "3" "/proc/cpufreq/cpufreq_power_mode"

    ########################
    # Max GPU Frequency
    ########################
    if [ -d /proc/gpufreq ]; then
        gpu_freq=$(cat /proc/gpufreq/gpufreq_opp_dump | /vendor/bin/grep -o 'freq = [0-9]*' | sed 's/freq = //' | sort -nr | head -n 1)
        apply "$gpu_freq" /proc/gpufreq/gpufreq_opp_freq
    elif [ -d /proc/gpufreqv2 ]; then
        apply 0 /proc/gpufreqv2/fix_target_opp_index
    fi

    ########################
    # EAS/HMP Switch
    ########################
    apply "0" /sys/devices/system/cpu/eas/enable

    ########################
    # Disable GPU Power Limiter
    ########################
    GPU_PWR_LIMIT_FILE="/proc/gpufreq/gpufreq_power_limited"
    if [ -f "$GPU_PWR_LIMIT_FILE" ]; then
        apply "ignore_batt_oc 1" "$GPU_PWR_LIMIT_FILE"
        apply "ignore_batt_percent 1" "$GPU_PWR_LIMIT_FILE"
        apply "ignore_low_batt 1" "$GPU_PWR_LIMIT_FILE"
        apply "ignore_thermal_protect 1" "$GPU_PWR_LIMIT_FILE"
        apply "ignore_pbm_limited 1" "$GPU_PWR_LIMIT_FILE"
    fi

    ########################
    # Battery and Power Limiter
    ########################
    apply "0" /proc/perfmgr/syslimiter/syslimiter_force_disable
    apply "stop 1" /proc/mtk_batoc_throttling/battery_oc_protect_stop

    ########################
    # Eara Thermal
    ########################
    apply "0" /sys/kernel/eara_thermal/enable

    ########################
    # UFS / DVFS Governors
    ########################
    apply "0" "/sys/devices/platform/10012000.dvfsrc/helio-dvfsrc/dvfsrc_req_ddr_opp"
    apply "0" "/sys/kernel/helio-dvfsrc/dvfsrc_force_vcore_dvfs_opp"
    apply "performance" "/sys/class/devfreq/mtk-dvfsrc-devfreq/governor"
    apply "performance" "/sys/devices/platform/soc/1c00f000.dvfsrc/mtk-dvfsrc-devfreq/devfreq/mtk-dvfsrc-devfreq/governor"

    ########################
    # GED Parameters
    ########################
    for param in \
        "ged_smart_boost 1" \
        "boost_upper_bound 100" \
        "enable_gpu_boost 1" \
        "enable_cpu_boost 1" \
        "ged_boost_enable 1" \
        "boost_gpu_enable 1" \
        "gpu_dvfs_enable 1" \
        "gx_frc_mode 1" \
        "gx_dfps 1" \
        "gx_force_cpu_boost 1" \
        "gx_boost_on 1" \
        "gx_game_mode 1" \
        "gx_3D_benchmark_on 1" \
        "gx_fb_dvfs_margin 100" \
        "gx_fb_dvfs_threshold 100" \
        "gpu_loading 100000" \
        "cpu_boost_policy 1" \
        "boost_extra 1" \
        "is_GED_KPI_enabled 0" \
        "ged_force_mdp_enable 1" \
        "force_fence_timeout_dump_enable 0" \
        "gpu_idle 0"; do
        key=$(echo "$param" | cut -d' ' -f1)
        value=$(echo "$param" | cut -d' ' -f2-)
        if [ -f "/sys/module/ged/parameters/$key" ]; then
            apply "$value" "/sys/module/ged/parameters/$key"
        fi
    done

    ########################
    # FPSGO Parameters
    ########################
    for param in boost_affinity boost_LR xgf_uboost xgf_extra_sub gcc_enable gcc_hwui_hint; do
        if [ -f "/sys/module/mtk_fpsgo/parameters/$param" ]; then
            apply "1" "/sys/module/mtk_fpsgo/parameters/$param"
        fi
    done
    FPSGO_ENABLE="/sys/pnpmgr/fpsgo_boost/boost_enable"
    [ -f "$FPSGO_ENABLE" ] && apply "1" "$FPSGO_ENABLE"

    ########################
    # GPU Power Policy
    ########################
    # Set Mali GPU power_policy ke always_on jika path tersedia
mali_path=$(find /sys/class/devfreq/ -type d -iname "*.mali" -print -quit 2>/dev/null)

if [ -n "$mali_path" ]; then
    power_policy_file="$mali_path/device/power_policy"
    if [ -f "$power_policy_file" ]; then
        echo "always_on" > "$power_policy_file"
        echo "[INFO] Mali power_policy set to always_on at $mali_path"
    else
        echo "[WARN] power_policy file tidak ditemukan di $mali_path"
    fi
else
    echo "[WARN] Mali devfreq path tidak ditemukan"
fi
}
###############################################
# # # # # # # SNAPDRAGON PERFORMANCE # # # # # # #
###############################################
snapdragon_performance() {
safe_toast "$snap"
    # Qualcomm CPU Bus and DRAM frequencies
    for path in /sys/class/devfreq/*cpu-ddr-latfloor*; do
        apply "performance" $path/governor
    done &

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

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

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

    if [ -d /sys/devices/system/cpu/bus_dcvs/LLCC ]; then
        freq=$(max /sys/devices/system/cpu/bus_dcvs/LLCC/available_frequencies)
        for path in /sys/devices/system/cpu/bus_dcvs/LLCC/*/max_freq; do
            apply $freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/LLCC/*/min_freq; do
            apply $freq $path
        done &
    fi

    if [ -d /sys/devices/system/cpu/bus_dcvs/L3 ]; then
        freq=$(max /sys/devices/system/cpu/bus_dcvs/L3/available_frequencies)
        for path in /sys/devices/system/cpu/bus_dcvs/L3/*/max_freq; do
            apply $freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/L3/*/min_freq; do
            apply $freq $path
        done &
    fi

    if [ -d /sys/devices/system/cpu/bus_dcvs/DDR ]; then
        freq=$(max /sys/devices/system/cpu/bus_dcvs/DDR/available_frequencies)
        for path in /sys/devices/system/cpu/bus_dcvs/DDR/*/max_freq; do
            apply $freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/DDR/*/min_freq; do
            apply $freq $path
        done &
    fi

    if [ -d /sys/devices/system/cpu/bus_dcvs/DDRQOS ]; then
        freq=$(max /sys/devices/system/cpu/bus_dcvs/DDRQOS/available_frequencies)
        for path in /sys/devices/system/cpu/bus_dcvs/DDRQOS/*/max_freq; do
            apply $freq $path
        done &
        for path in /sys/devices/system/cpu/bus_dcvs/DDRQOS/*/min_freq; do
            apply $freq $path
        done &
    fi

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

    if [ -d $gpu_path ]; then
        freq=$(max $gpu_path/available_frequencies)
        apply $freq $gpu_path/min_freq
        apply $freq $gpu_path/max_freq
    fi

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

    # Adreno Boost
    apply 3 /sys/class/kgsl/kgsl-3d0/devfreq/adrenoboost
}
exynos_performance() {
safe_toast "$exy"
    # GPU Frequency
    gpu_path="/sys/kernel/gpu"
    [ -d "$gpu_path" ] && {
        max_freq=$(max "$gpu_path/gpu_available_frequencies")
        apply "$max_freq" "$gpu_path/gpu_max_clock"
    }
    mali_sysfs=$(find /sys/devices/platform/ -iname "*.mali" -print -quit 2>/dev/null)
    apply always_on "$mali_sysfs/power_policy"

    # DRAM and Buses Frequency
    [ $DEVICE_MITIGATION -eq 0 ] && {
        for path in /sys/class/devfreq/*devfreq_mif*; do
            [ $LITE_MODE -eq 1 ] &&
                devfreq_mid "$path" ||
                devfreq_max "$path"
        done &
    }
    
}

###############################################
# # # # # # # UNISOC PERFORMANCE # # # # # # #
###############################################
unisoc_performance() {
    safe_toast "$uni"
    local gpu_path="/sys/kernel/gpu"
    local freq

    # Tentukan sumber frekuensi GPU
    for src in gpu_available_frequencies gpu_freq_table; do
        if [ -f "$gpu_path/$src" ]; then
            freq=$(max "$gpu_path/$src")
            break
        fi
    done

    if [ -z "$freq" ]; then
        echo "[WARN] GPU frequency source tidak ditemukan"
        return 1
    fi

    # Apply frekuensi ke min/max GPU clock tanpa array
    for clk in gpu_min_clock gpu_max_clock; do
        [ -f "$gpu_path/$clk" ] && apply "$freq" "$gpu_path/$clk"
    done

    # Nonaktifkan thermal management (tmu) di semua Mali
    for mali_fs in /sys/devices/platform/*.mali; do
        [ -f "$mali_fs/tmu" ] && apply "0" "$mali_fs/tmu"
    done

    # GPU Frequency
    gpu_path=$(find /sys/class/devfreq/ -type d -iname "*.gpu" -print -quit 2>/dev/null)
    [ -n "$gpu_path" ] && {
        if [ "$LITE_MODE" -eq 0 ]; then
            devfreq_maxf "$gpu_path"
        else
            devfreq_mid "$gpu_path"
        fi
    }
}

###############################################
# # # # # # # TENSOR PERFORMANCE # # # # # # #
###############################################
tensor_performance() {
safe_toast "$tensor"
    # GPU Frequency
    gpu_path=$(find /sys/devices/platform/ -type d -iname "*.mali" -print -quit 2>/dev/null)
    [ -n "$gpu_path" ] && {
        max_freq=$(max "$gpu_path/available_frequencies")
        apply "$max_freq" "$gpu_path/scaling_max_freq"
    }

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

###############################################
# # # # # # # PERFORMANCE PROFILE! # # # # # # #
###############################################
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
}
performance_profile() {
    # Power level settings
    for pl in /sys/devices/system/cpu/perf; do
        apply 1 "$pl/gpu_pmu_enable"
        apply 1 "$pl/fuel_gauge_enable"
        apply 1 "$pl/enable"
        apply 1 "$pl/charger_enable"
    done

    # Set Governor Game
    set_governor "performance"

        if [ -d /proc/ppm ]; then
            cluster=0
            for path in /sys/devices/system/cpu/cpufreq/policy*; do
                cpu_maxfreq=$(cat "$path/cpuinfo_max_freq")

                apply "$cluster $cpu_maxfreq" "/proc/ppm/policy/hard_userlimit_max_cpu_freq"
                apply "$cluster $cpu_maxfreq" "/proc/ppm/policy/hard_userlimit_min_cpu_freq"
                ((cluster++))

            done
        fi
        for path in /sys/devices/system/cpu/*/cpufreq; do
            cpu_maxfreq=$(cat "$path/cpuinfo_max_freq")

            apply "$cpu_maxfreq" "$path/scaling_max_freq"
            apply "$cpu_maxfreq" "$path/scaling_min_freq"

        done

    # VM Cache Pressure
    apply "40" "/proc/sys/vm/vfs_cache_pressure"
    apply "3" "/proc/sys/vm/drop_caches"

    # Workqueue settings
    apply "N" /sys/module/workqueue/parameters/power_efficient
    apply "N" /sys/module/workqueue/parameters/disable_numa
    apply "0" /sys/kernel/eara_thermal/enable
    apply "0" /sys/devices/system/cpu/eas/enable
    apply "1" /sys/devices/system/cpu/cpu2/online
    apply "1" /sys/devices/system/cpu/cpu3/online

    # Schedtune Settings
    for path in /dev/stune/*; do
        base=$(basename "$path")
        if [[ "$base" == "top-app" || "$base" == "foreground" ]]; then
            apply 30 "$path/schedtune.boost"
            apply 1 "$path/schedtune.sched_boost_enabled"
        else
            apply 30 "$path/schedtune.boost"
            apply 1 "$path/schedtune.sched_boost_enabled"
        fi
        apply 0 "$path/schedtune.prefer_idle"
        apply 0 "$path/schedtune.colocate"
    done

    # Power level settings
    for pl in /sys/devices/system/cpu/perf; do
        apply 1 "$pl/gpu_pmu_enable"
        apply 1 "$pl/fuel_gauge_enable"
        apply 1 "$pl/enable"
        apply 1 "$pl/charger_enable"
    done

    # CPU max tune percent
    apply 1 /proc/sys/kernel/perf_cpu_time_max_percent

    # Sched Energy Aware
    apply 1 /proc/sys/kernel/sched_energy_aware

    # 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
    # Disable battery saver module
    [ -f /sys/module/battery_saver/parameters/enabled ] && {
        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
    }

    # Disable split lock mitigation
    apply 0 /proc/sys/kernel/split_lock_mitigate

    # Schedfeatures settings
    if [ -f "/sys/kernel/debug/sched_features" ]; then
        apply NEXT_BUDDY /sys/kernel/debug/sched_features
        apply NO_TTWU_QUEUE /sys/kernel/debug/sched_features
    fi
    gms

    case "$(cat /data/local/tmp/thunder_default/soc)" in
    1) mediatek_performance ;;
    2) snapdragon_performance ;;
    3) exynos_performance ;;
    4) unisoc_performance ;;
    5) tensor_performance ;;
    esac
}
# Activating Performance 

cmd display set-user-disabled-hdr-types 1 2 3 4
performance_profile
ppm_max
cpu_max

echo "performance" > "/data/adb/modules/RaiRin-AI/cortex/thunderclash/current_mode"


su -lp 2000 -c "cmd notification post -S bigtext -t 'RaiRin-AI' RaiRin 'Game Detected — Perfomance mode ON'"
sleep 1
su -lp 2000 -c "/system/bin/cmd notification post \
    -t 'RaiRin-AI' \
    -i file://$TMP_ICON \
    -I file://$TMP_ICON \
    'RaiRin' 'Game Detected — Perfomance mode ON'"
exit 0


