#!/bin/bash

# Give default values to parameters
Servo=0
Min=50
Max=250
Med=150

OPTIND=1

while getopts ":hs:m:M:c:" opt
do
    case "$opt" in
    h) show_help
       exit 0
       ;;
    s) Servo=$OPTARG;;
    m) Min=$OPTARG;;
    M) Max=$OPTARG;;
    c) Med=$OPTARG;;
    \?)
        echo "Invalid option: -$OPTARG" >&2
        show_help >&2
        exit 1
        ;;
    :)
        echo "Option -$OPTARG requires an argument"
        exit 2
        ;;
    esac
done

function show_help
{
    echo "Usage: $0 [-h] [-s servo] [-m min] [-M max] [-c center]"
    echo
    echo -n "  "
    print_values
}

function print_values
{
    echo "Selected servo is $Servo"
}

echo "This script will test your esc and rotate the motor at different speeds."
echo "  Be careful to attach you motor before starting this script."

print_values

read -p "Continue ? Yes (y/Y) or No (n/N) " res
case "$res" in
    y|Y) echo;;
    *)
        exit 1
        ;;
esac

function motor
{
    echo $Servo=$1 > /dev/servoblaster
}

echo -n "Starting your motor in "
for i in $(seq 5 -1 1)
do
    echo -n "$i"
    sleep 0.25
    for j in $(seq 3)
    do
        echo -n "."
        sleep 0.25
    done
done
echo " Go !"
sleep 0.5

function test_motor
{
    Msg=$1
    First=$2
    Last=$3
    Reverse=$4
    Step=$(echo "scale=1 ; ( $Last - $First ) / 10" | bc)
    Incr=$(echo "scale=0 ; ( $Last - $First ) / 10" | bc)
    if [ $Incr -gt 0 ]
    then
        if [ $Reverse = "False" ]
        then
            Pourcent=0
            Incr=10
        else
            Pourcent=100
            Incr=-10
        fi
    else
        if [ $Reverse = "False" ]
        then
            Pourcent=100
            Incr=-10
        else
            Pourcent=0
            Incr=10
        fi
    fi

    echo $Msg
    for i in $(seq $First $Step $Last)
    do
        echo -n "$Pourcent% "
        Val=$(echo "scale=0 ; $i * 10 / 10" | bc)
        motor $i
        Pourcent=$(expr $Pourcent + $Incr)
        sleep 0.5
    done
    echo
    sleep 1
    echo
}

test_motor "Forward speed increasing until maximum speed:" $Med $Max False
test_motor "Forward speed decreasing until motor stops:" $Max $Med False
test_motor "Reverse speed increasing until maximum reverse speed:" $Med $Min True
test_motor "Reverse speed decreasing until motor stops:" $Min $Med True
