#!/usr/bin/bash

# ncid-notify
# usage: ncid --no-gui --module ncid-notify

# Last edited: May 18, 2021

# Copyright (c) 2001-2021 by
#   John L. Chmielewski <jlc@users.sourceforge.net>
#   Todd Andrews <tandrews@users.sourceforge.net>

# sends an NCID notification to an iOS device

# Android devices not supported anymore.  Notify My Android (NMN) shutdown
# on May 24, 2018.

ConfigDir=/etc/ncid/conf.d
ConfigFile=$ConfigDir/ncid-notify.conf

# Requirement for iOS:
# The Prowl (Growl client for iOS) app from the app store
# Free registration at the Prowl website <http://www.prowlapp.com/>
# Generated API key to place in configuration file.

# Module Requires:
# Generated API key from Prowl
# bash 2.0 or higher
# curl
# CA certificates

### defaults if not using config file ###
###  see $ConfigFile for description  ###
allowed_types="ALLTYPES"
notify_priority=0
notify_clock="12"
notify_url=

# Prowl defaults
notify_apikey_prowl=
notify_apikeyfile_prowl=$ConfigDir/key-prowl-api
notify_hvolkey_prowl=""
notify_hvolkeyfile_prowl=$ConfigDir/key-prowl-provider
notify_protocol_prowl="https"
# CALLTYPE
notify_application_for_calls_prowl='NCID'
notify_event_for_calls_prowl='$DESC'
notify_notification_for_calls_prowl='$NAME $FNMBR $LINE'
# MSGTYPE
notify_application_for_messages_prowl='NCID'
notify_event_for_messages_prowl='$DESC'
notify_notification_for_messages_prowl='$MESG'

[ -f $ConfigFile ] && . $ConfigFile

# backward compatibility for pre-NCID 1.8 config files
             [ -n "$notify_types" ] &&                          allowed_types=$notify_types

 [ -n "$notify_application_prowl" ] &&     notify_application_for_calls_prowl=$notify_application_prowl
 [ -n "$notify_application_prowl" ] &&  notify_application_for_messages_prowl=$notify_application_prowl
       [ -n "$notify_event_prowl" ] &&           notify_event_for_calls_prowl=$notify_event_prowl
       [ -n "$notify_event_prowl" ] &&        notify_event_for_messages_prowl=$notify_event_prowl
[ -n "$notify_notification_prowl" ] &&    notify_notification_for_calls_prowl=$notify_notification_prowl
[ -n "$notify_notification_prowl" ] && notify_notification_for_messages_prowl=$notify_notification_prowl

# === Start of common module script routines - ncid-modules-common.sh

# Last edited: Jun 30, 2022

# Before this code is executed:
#    - set $allowed_types as desired
#
# After this code is executed:
#    - stdin will have been read into $DATE, $TIME, $NMBR, $NAME, etc.
#    - $found=1 if $TYPE is in $allowed_types; otherwise $found will be null
#    - $type_cat(egory) will be "CALLTYPE", "MSGTYPE", or "UNKNOWNTYPE"
#    - $type_smart_phone is "Y" for both smart phone calls and messages,
#      otherwise $type_smart_phone will be null
#    - $type_desc(ription) will be set to human readable verbiage

# $allowed_types can be:
#    - any mix of zero or more individual call/line types separated by spaces
#    - any mix of zero or more type categories separated by spaces
#    - the special category "ALLTYPES"
#    - null, which defaults to "ALLTYPES"
#
# If $allowed_types includes spaces, you must surround the list with quotes.
#
# Note that "ALLTYPES" causes **any** $TYPE to be accepted.
#
# Examples:
#    allowed_types="CALLTYPE"
#    allowed_types="CALLTYPE MSGTYPE"
#    allowed_types="CID MSGTYPE HUP"

# input is always 12 lines
INPUT="DATE TIME NMBR NAME LINE TYPE MESG MTYPE FNMBR CTRY LOCA CARI"
for i in $INPUT; do read $i; done

# if input is from a call:
# input: DATE\nTIME\nNMBR\nNAME\nLINE\nTYPE\n""\n""\nFNMBR\nCTRY\nLOCA\nCARI\n
#
# if input is from a message
# input: DATE\nTIME\nNMBR\nNAME\nLINE\nTYPE\nMESG\nMTYPE\nFNMBR\nCTRY\nLOCA\nCARI\n

# determine $TYPE category and description
  type_cat="UNKNOWNTYPE"
  type_desc="Unknown Call Type ($TYPE)"
  type_smart_phone=

case "$TYPE" in

  BLK) type_cat=CALLTYPE;  type_smart_phone= ; type_desc="Blacklisted Call Blocked";;
  CID) type_cat=CALLTYPE;  type_smart_phone= ; type_desc="Incoming Call";;
  HUP) type_cat=CALLTYPE;  type_smart_phone= ; type_desc="Blacklisted Call Hangup";;
  MWI) type_cat=CALLTYPE;  type_smart_phone= ; type_desc="Voicemail Message Waiting";;
  OUT) type_cat=CALLTYPE;  type_smart_phone= ; type_desc="Outgoing Call";;
  PID) type_cat=CALLTYPE;  type_smart_phone=Y; type_desc="Caller ID from a smart phone";;
  PUT) type_cat=CALLTYPE;  type_smart_phone=Y; type_desc="Outgoing Smart Phone Call";;
  RID) type_cat=CALLTYPE;  type_smart_phone= ; type_desc="Ringback Call";;
  WID) type_cat=CALLTYPE;  type_smart_phone= ; type_desc="Call Waiting Caller ID";;

  MSG)  type_cat=MSGTYPE;  type_smart_phone= ; type_desc="Message";;
  NOT)  type_cat=MSGTYPE;  type_smart_phone=Y; type_desc="Notice of a smart phone message";;

esac

# Is this $TYPE one that can be processed by this module?
found=
if [ -z "$allowed_types" ]
then
    allowed_types="ALLTYPES"
    found=1
else
    for i in $allowed_types
    do
        if   [ $i = "ALLTYPES" ];  then found=1; break;
        elif [ $i = "$type_cat" ]; then found=1; break;
        elif [ $i = "$TYPE" ];     then found=1; break;
        fi
    done
fi

# === End of common module script routines - ncid-modules-common.sh

# exit if call type is unknown
[ -z "$found" ] && exit 1

# place scalar service-specific variables from ncid-notify.conf into
# an indexed array to make it easier to add multiple services
# service is always 'prowl'

                  notify_service[1]="prowl"

                 notify_protocol[1]="$notify_protocol_prowl"
                   notify_apikey[1]="$notify_apikey_prowl"
               notify_apikeyfile[1]="$notify_apikeyfile_prowl"
                  notify_hvolkey[1]="$notify_hvolkey_prowl"
              notify_hvolkeyfile[1]="$notify_hvolkeyfile_prowl"
              notify_application[1]="" # placeholder
                    notify_event[1]="" # placeholder
             notify_notification[1]="" # placeholder
    notify_application_for_calls[1]="$notify_application_for_calls_prowl"
          notify_event_for_calls[1]="$notify_event_for_calls_prowl"
   notify_notification_for_calls[1]="$notify_notification_for_calls_prowl"
 notify_application_for_messages[1]="$notify_application_for_messages_prowl"
       notify_event_for_messages[1]="$notify_event_for_messages_prowl"
notify_notification_for_messages[1]="$notify_notification_for_messages_prowl"


# determine settings for each service
count=0
for i in "${notify_service[@]}"
do
    count=$(($count + 1))
    case $i in
            "") continue;; # handle sparse array element
         prowl) option[$count]="-F"
                www[$count]=${notify_protocol[$count]}://prowl.weks.net/publicapi/add;;
             *) exit 1;;
    esac
done

# if notify_apikeyfile exists & notify_apikey blank, get api key from file
count=0
found=""
for i in "${notify_service[@]}"
do
    count=$(($count + 1))
	[ -z "$i" ] && continue # handle sparse array element
    [ -f "${notify_apikeyfile[$count]}" -a ! "${notify_apikey[$count]}" ] &&
        notify_apikey[$count]=`cat ${notify_apikeyfile[$count]}`
    # api key is required
    if [ "${notify_apikey[$count]}" ]
	   then
	   found=1
	else
	   notify_service[$count]="" # no api key so clear this service from being used
	fi
done

# must have at least one service
[ -z "$found" ] && exit 1

# similarly for the optional high volume keys
count=0
for i in "${notify_service[@]}"
do
    count=$(($count + 1))
    [ -z "$i" ] && continue # handle sparse array element
    [ -f "${notify_hvolkeyfile[$count]}" -a ! "${notify_hvolkey[$count]}" ] &&
        notify_hvolkey[$count]=`cat ${notify_hvolkeyfile[$count]}`
done

# set notification description
  DESC="${type_desc}"
  if [ "$type_cat" = "MSGTYPE" ]; then
     DATE=`date '+%m/%d/%Y'`
     TIME=`date '+%H:%M'`
  fi

[ "$TIME" -a "$notify_clock" = "12" ] && \
{
    # convert time from 24 hour format to 12 hour format
    hour=${TIME/:*/}
    minute=${TIME/*:/}
    if [ -z "$hour" ]
    then
        hour=12 ampm=PM
    else
        if [ $hour -lt 12 ]
        then
            [ $hour -eq 0 ] && hour=12
            ampm=AM
        elif [ $hour -eq 12 ]
        then
            ampm=PM
        else
            hour=$(($hour - 12))
            ampm=PM
        fi
    fi
    notify_time="$hour:$minute $ampm"
} || notify_time=$TIME

# reset TIME to $notify_time so the 'eval' below will use the newly
# reformatted 12 hour time
TIME=$notify_time

# send notification
count=0
for i in "${notify_service[@]}"
do
    count=$(($count + 1))
	[ -z "$i" ] && continue # handle sparse array element

    if [ "$type_cat" = "MSGTYPE" ]
       then
           notify_application[$count]="${notify_application_for_messages[$count]}"
                 notify_event[$count]="${notify_event_for_messages[$count]}"
          notify_notification[$count]="${notify_notification_for_messages[$count]}"
          clickable_url=""
       else
           notify_application[$count]="${notify_application_for_calls[$count]}"
                 notify_event[$count]="${notify_event_for_calls[$count]}"
          notify_notification[$count]="${notify_notification_for_calls[$count]}"
          # determine if url should be used
          [ "$notify_url" ] && \
          {
              # no safeguard for number being word(s)
              # set clickable url to the url + raw number
              rawnum=${NMBR//-/}
              clickable_url=$notify_url$rawnum
          }
    fi

	 notify_application[$count]=`eval echo ${notify_application[$count]}`
	       notify_event[$count]=`eval echo ${notify_event[$count]}`
	notify_notification[$count]=`eval echo ${notify_notification[$count]}`

	# providerkey  used by Prowl

    curl \
        ${option[$count]} apikey="${notify_apikey[$count]}" \
        ${option[$count]} application="${notify_application[$count]}" \
        ${option[$count]} event="${notify_event[$count]}" \
        ${option[$count]} description="${notify_notification[$count]}" \
		${option[$count]} priority="$notify_priority" \
        ${option[$count]} developerkey="${notify_hvolkey[$count]}" \
        ${option[$count]} url="$clickable_url" \
        ${www[$count]}
done

exit 0
