#!/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 values are:"
    echo "    servo  = $Servo"
    echo "    min    = $Min"
    echo "    max    = $Max"
    echo "    center = $Med"
}


function print_wait
{
    echo $*
    echo "    When ok, press Enter"
    read enter
}

echo "This script will help you to calibrate your ESC EZRUN."
print_values
echo
read -p "Continue ? Yes (y/Y) or No (n/N) " res
case "$res" in 
    y|Y) echo;;
    *) 
        exit 1
        ;;
esac

print_wait " 1. Switch off your ESC-EZRUN. Verify that it's connected to R-Pi."

print_wait " 2. Press the red button next to the ESC switch and switch on the ESC" "    When the red led blink and you hear a beep, release the red button."
echo $Servo=$Med > /dev/servoblaster

print_wait " 3. Press the red button. The green led should flash once"
echo $Servo=$Max > /dev/servoblaster

print_wait "4. Press the red button. The green led should flash twice"
echo $Servo=$Min > /dev/servoblaster

print_wait "5. Press the red button. The green led should flash three times"

echo "Calibrating process if finihed."
echo "You can try the test program to verify that all is OK."
echo "Have fun!"
