#!/system/bin/sh
#本脚本由搞机助手自动创建
#作者：by：Han | 情非得已c
#请不要试图篡改本脚本，否则一切后果自负，已安装版本：v2021011815(2021011815)
#特别鸣谢Magisk提供服务支持：by topjohnwu



Time() {
    date '+%F  %H:%M:%S'
}

MODDIR=${0%/*}
Charging_control=/sys/class/power_supply/battery/input_suspend
Charging_control2=/sys/class/power_supply/battery/charging_enabled
level=/sys/class/power_supply/battery/capacity
log=/storage/emulated/0/Android/MIUI12.5+/充电保护.log

Delay=5m
DEBUG=true
Status=0
Status2=1

unset L H
[[ ! -f $Charging_control && ! -f $Charging_control2 ]] && exit 1
echo "当前模块版本：v2021011815（2021011815）" >$log
echo "时间：`Time`" >>$log
echo "脚本已执行正在保护充电，电量：$(cat $level)%" >>$log
sleep 2m

if [ -f "/storage/emulated/0/Android/MIUI12.5+/充电保护.conf" ]; then 
     source /storage/emulated/0/Android/MIUI12.5+/充电保护.conf
else
     Start=90
     Stop=100
     Set_Greedy_Time=2m
    fi

until false; do
    [[ -n $Delay ]] && sleep $Delay
    Power=$(cat $level)%
    [[ `wc -c < $log` -ge 9338880 ]] && rm -f $log
    $DEBUG && echo "`Time`，正在保护充电中，电量：$Power" >>$log
    [[ -f $Charging_control ]] && Status=`cat $Charging_control`
    [[ -f $Charging_control2 ]] && Status2=`cat $Charging_control2`
    if [[ $(cat $level) -ge $Stop ]]; then
        if [[ $Status -eq 0 || $Status2 -eq 1 ]]; then
            if [[ -n $L ]]; then
                L=$L
            elif [[ -z $L ]]; then
                [[ -n $Set_Greedy_Time ]] && sleep $Set_Greedy_Time
                [[ -f $Charging_control ]] && echo 1 >$Charging_control
                [[ -f $Charging_control2 ]] && echo 0 >$Charging_control2
                L=1
                unset H
                $DEBUG && echo "`Time`，已在$Power时停止充电" >>$log
            fi
        fi
    elif [[ $(cat $level) -le $Start ]]; then
        if [[ $Status -eq 1 || $Status2 -eq 0 ]]; then
            if [[ -n $H ]]; then
                H=$H
            elif [[ -z $H ]]; then
                [[ -f $Charging_control ]] && echo 0 >$Charging_control
                [[ -f $Charging_control2 ]] && echo 1 >$Charging_control2
                H=1
                unset L
                $DEBUG && echo "`Time`，已在$Power时重新启用充电" >>$log
            fi
        fi
    fi
done
