#!/bin/sh /etc/rc.common

START=99

start() {
    . /lib/functions.sh

    # Unload pwm_fan module if loaded
    if lsmod | grep -q pwm_fan; then
        rmmod pwm_fan
    fi

    local period=40000

    # Initialize PWM interface
    init_pwm() {
        echo 0 > /sys/class/pwm/pwmchip0/export
        echo $period > /sys/class/pwm/pwmchip0/pwm0/period
        echo normal > /sys/class/pwm/pwmchip0/pwm0/polarity
    }

    # Set fan speed by percentage
    set_fan_speed_percentage() {
        local percentage=$1
        local duty_cycle=$(( (percentage * period) / 100 ))
        echo $duty_cycle > /sys/class/pwm/pwmchip0/pwm0/duty_cycle
        echo 1 > /sys/class/pwm/pwmchip0/pwm0/enable
    }

    # Disable fan
    disable_fan() {
        echo 0 > /sys/class/pwm/pwmchip0/pwm0/enable
    }

    # Get temperature
    get_temperature() {
        temp=$(cat /sys/class/thermal/thermal_zone0/temp)
        temp_c=$((temp / 1000))
        echo $temp_c
    }

    # Temperature control logic
    control_fan_based_on_temp() {
        temp=$(get_temperature)

        if [ "$temp" -lt "$temp_low" ]; then
            set_fan_speed_percentage 0
        elif [ "$temp" -ge "$temp_low" ] && [ "$temp" -lt "$temp_mid" ]; then
            set_fan_speed_percentage $speed_low
        elif [ "$temp" -ge "$temp_mid" ] && [ "$temp" -lt "$temp_high" ]; then
            set_fan_speed_percentage $speed_mid
        else
            set_fan_speed_percentage $speed_high
        fi
    }

    # Initialize PWM
    init_pwm

    # Define a function to clean up resources on shutdown
    cleanup() {
        echo "Stopping fan control..."
        disable_fan
        exit 0
    }

    # Trap signals for cleanup
    trap cleanup SIGTERM SIGINT

    # Main loop running in the background
    control_fan_based_on_temp_loop() {
        while true; do
            # Reload configuration parameters in each loop
            config_load fancontrol
            config_get temp_low settings temp_low
            config_get temp_mid settings temp_mid
            config_get temp_high settings temp_high
            config_get speed_low settings speed_low
            config_get speed_mid settings speed_mid
            config_get speed_high settings speed_high
            config_get fan_enabled settings fan_enabled

            if [ "$fan_enabled" -eq 1 ]; then
                control_fan_based_on_temp
            else
                disable_fan
            fi

            sleep 10
        done
    }

    # Run the loop in the background
    control_fan_based_on_temp_loop &
}
