#!/bin/sh

# if an error occurs, break immediately
set -e

# Variables from Kannel sms gateway
sms_phone="$SMS_PHONE"
sms_fromphone="$1"
app="$2"
shift 2
msg="$*"

# Settings for the "mail" outgoing email command
export smtp=mail.bitbase.dk
export from=hp@fossasia.org
export sender="$from"

file=/var/www/vhosts/www-sms/sms.localnet/index.txt
mail_subject="[sms] phone $sms_fromphone"
mail_recipients="hp@fossasia.org mb@fossasia.org"

doit() {
	# Replace or append to phone list
	perl -i -s -p \
		-e 's/^(\Q$number\E) .*/$1 $name/ and $seen++;' \
		-e '$_ .= "$number $name\n" if (eof and !$seen);' \
		-- -number="$sms_fromphone" -name="$msg" "$file"
	# Send message (...to stdout if invoked from cmdline)
	if [ -n "$sms_phone" ]; then
		mail -s "$mail_subject" $mail_recipients
	else
		cat
	fi
}

# Check keyword and break after processing if it matches
case "$app" in
  phone)
	cat <<EOF | doit
Phone list auto-updated with this entry:

  $sms_fromphone $msg

See the complete up-to-date phone list at http://sms.localnet/
EOF
	exit 1
	;;
esac