#!/bin/bash
# find location of the script
# ## TODO Softcode this.
pwd=~/src/sms

# set user variables. (see config_example)
. ~/src/sms-data/config

# Where to store the tempfile when using vim
sms_tempfile=~/.sms_temp
###########
n=1;
for entry in $(cat $pwd/../sms-data/contacts);do
echo $n $entry;
n=$(($n+1))
done;

while true
do
  # (1) prompt user for recipent, and read command line argument
   read -p "To: " toinput
  # (2) handle the input we were given
       case $toinput in
            [\+0][0-9]* ) nr=$toinput; break;;
            [1-9]* )    n=0;
                        for entry in $(cat $pwd/../sms-data/contacts);do
                            n=$(($n+1))
                            if (($n==$toinput)); then
                                nr=$(echo $entry|cut -d ',' -f2)
                            fi
                        done
                    break;;
                * ) echo 'Please enter the nr. of an entry or a full phonenumber';;
        esac
done

tempdata=0

  # (3) prompt user for message content, and read command line argument
read -p "Message: " messageinput

case $messageinput in
    sed )
        echo -n 'Message: '
        messageinput=$(sed '/^$/q');;
    cat )
        echo -n 'Message: '
        messageinput=$(cat);;
    vim )
        touch $sms_tempfile
        tempdata=1
        vim $sms_tempfile
        messageinput=$(cat $sms_tempfile);;
    * ) ;;
    esac

while true
do
      # (1) prompt user, and read command line argument
    read -p "Send message to $nr?[n] " answer
      # (2) handle the input we were given
     case $answer in
        [nN]* ) action=info;break;;
            * )  break;;
      esac
done
echo -----------
    curl http://www.sms-revolution.ch/API/httpsms.php -d user=$user \
    -d password=$password --data-urlencode "text=$messageinput" \
    -d to=$nr -d from=$from -d action=$action -d typ=$typ \
    -d timestamp=$timestamp -d return=$return -d httphead=$httphead

# TODO get a usable return value from curl and actualy make this work.
if (($tempdata == 1)); then
    if $(echo $response | grep 100); then
        rm $sms_tempfile
    else
        echo "response was not 100, leaving tempfile where it is"
    fi
fi