#!/usr/bin/env bash

source $(dirname $0)/oref0-bash-common-functions.sh || (echo "ERROR: Failed to run oref0-bash-common-functions.sh. Is oref0 correctly installed?"; exit 1)

# Something like this:
# https://maker.ifttt.com/trigger/{event}/with/key/MyKey
IFTTT_TRIGGER=${IFTTT_TRIGGER-${1}}
IFTTT_NOTIFY_USAGE="${2-pump model}"

usage "$@" <<EOF
Usage: $self <IFTTT_TRIGGER> <NOTIFY_USAGE>

## Setup IFTTT Account

You need to create an account and connect to the Maker channel and the
notification channel of your choice. I use pushover as I already had the app
and it allows me more control over the notification on my phone. 

## Create an IF recipe
The trigger is the maker channel. You can customize the notification message
if you wish.

## Get the event trigger
On the Maker channel there is a "how to trigger" link. Copy and paste the url
for the example curl command, be sure to change the event name field.
The URL, something like:

    https://maker.ifttt.com/trigger/{event}/with/key/MyKey

You can pass the IFTTT_TRIGGER, which is the trigger URL as the first
argument, or define it as an environment variable in your crontab.

Command line:

      $self https://maker.ifttt.com/trigger/{event}/with/key/MyKey


Crontab:
      IFTTT_TRIGGER=https://maker.ifttt.com/trigger/{event}/with/key/MyKey

By default $self will check that the stick works, and notify the IFTTT_TRIGGER
endpoint only if the the stick fails to check out.  If the stick diagnostics
indicate the carelink stick is working, $self will run:

      openaps use $IFTTT_NOTIFY_USAGE

You can specify which openaps use command to use in the second argument, or by
setting the IFTTT_NOTIFY_USAGE environment variable in crontab:

Command line, note the quotes, the second term must be passed as single word.

      $self https://maker.ifttt.com/trigger/{event}/with/key/MyKey 'pump model'

Crontab:

      IFTTT_NOTIFY_USAGE='pump model'

Author: @audiefile
EOF



case $1 in
env)
  echo PATH=$PATH
  env
  exit
  ;;
*)
  if [[ -z "$IFTTT_TRIGGER" || -z  "$IFTTT_NOTIFY_USAGE" ]] ; then
    help_message
    exit 1
  fi
  ;;
esac


# check carelink is working - if not send notification
# maybe switch:

mm-stick diagnose > /dev/null || curl -X POST $IFTTT_TRIGGER
# python -m decocare.stick $(python -m decocare.scan) >/dev/null || curl -X POST $IFTTT_TRIGGER
echo "Carelink Stick OK"

# check carelink can talk to pump - if not send notification
model=$(openaps use $IFTTT_NOTIFY_USAGE)
echo "Model: " $model
if [ -z "$model" ];
then
  echo "Model is empty"
  curl -X POST $IFTTT_TRIGGER
fi  

