#! /bin/sh
#
# Laptop mode tools module to handle CPU Hot Plugging
#


# Determine number cpu cores on machine
max_available_cpus() {
    CPU=/sys/devices/system/cpu/present
    if [ -f $CPU ]; then
        max_cpu=$(cat $CPU | cut -d '-' -f2);
        max_cpu=$(expr $max_cpu + 1);
        echo $max_cpu;
    else
        echo -1;
    fi
}


get_numeric_val() {
    num_cpu=`max_available_cpus`;

    case "$1" in
        "quarter")
            disable_cpus=$(echo $num_cpu*1/4 | bc);
            ;;
        "half")
            disable_cpus=$(echo $num_cpu*1/2 | bc);
            ;;
        "3quarter")
            disable_cpus=$(echo $num_cpu*3/4 | bc);
            ;;
        [0-9]*)
            disable_cpus=$1;
            ;;
    esac
}


if [ x$CONTROL_CPU_HOTPLUG = x1 ] || [ x$ENABLE_AUTO_MODULES = x1 -a x$CONTROL_CPU_HOTPLUG = xauto ]; then
	if [ $ON_AC -eq 1 ] ; then
		if [ "$ACTIVATE" -eq 1 ] ; then
			ECHO_VAL="$LM_AC_CPU_HOTPLUG"
		else
			ECHO_VAL="$NOLM_AC_CPU_HOTPLUG"
		fi
	else
		ECHO_VAL="$BATT_CPU_HOTPLUG"
	fi

	# To disable the CPU, write 0. So flip it here.
	if [ x$ECHO_VAL = x1 ]; then
		CPU_VAL=0;
	else
		CPU_VAL=1;
	fi

        counter=0;
        get_numeric_val $DISABLE_AVAILABLE_CPU

	for THISCPU in /sys/devices/system/cpu/cpu[0-9]* ; do
                if [ $counter -le $disable_cpus ]; then
                        counter=$(expr $counter + 1);
                else
                        break;
                fi

		if [ -e "$THISCPU/online" ]; then
			log "VERBOSE" "Bringing CPU $THISCPU to $ECHO_VAL";
			echo $CPU_VAL > $THISCPU/online;
		else
			log "VERBOSE" "CPU $THISCPU cannot be hot plugged";
		fi
	done
fi
