#! /bin/bash

red=/sys/class/pwm/pwmchip0
green=/sys/class/pwm/pwmchip1
blue=/sys/class/pwm/pwmchip2

for color in "$red" "$green" "$blue"; do
    if [ ! -d "$color/pwm0" ]; then
        echo 0 > $color/export
    fi
done

clamp()
{
    declare -i integer=$1
    declare -i min=$2
    declare -i max=$3
    if [[ $integer -lt $min ]]; then
        echo $min
    elif [[ $integer -gt $max ]]; then
        echo $max
    else
        echo $integer
    fi
}

red_dc=$(clamp $1 0 100)
green_dc=$(clamp $2 0 100)
blue_dc=$(clamp $3 0 100)
period=${4:-10000}
echo "R: $red_dc% G: $green_dc% B: $blue_dc% Period: $period ns"

for color in "$red" "$green" "$blue"; do
    echo 0 > $color/pwm0/duty_cycle
    echo $period > $color/pwm0/period
done

echo "$((red_dc * period / 100))" > $red/pwm0/duty_cycle
echo "$((green_dc * period / 100))" > $green/pwm0/duty_cycle
echo "$((blue_dc * period / 100))" > $blue/pwm0/duty_cycle

for color in "$red" "$green" "$blue"; do
    echo 1 > $color/pwm0/enable
done
