#!/usr/bin/env bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
source "$DIR/common"

# This is largely borrowed from:
# https://git.sr.ht/~mil/sxmo-utils/tree/master/item/scripts/modem/sxmo_modemmonitor.sh

# This is where sms messages will be stored

usage(){
	echo "checkSMS [options]"
	echo "Options:"
	echo "  -h|--help       Display this help text"
	echo "  -m|--modem      Specify a modem"
	echo "  --dry-run       Don't actually send the message"
}


mkdir -p "$SMS_DIR"

dryrun="false"

# Assume we want the first modem
# can be overwritten by the -m option
modem="$(mmcli -L | grep -oE 'Modem\/[0-9]+' | head -n 1 | cut -d'/' -f2)"


# Read the options and set stuff
while [[ $1 = -?* ]]; do
	case $1 in
		-h|--help) usage; exit;;
		-m|--modem) modem="$2"; shift ;;
		--dry-run) dryrun="true" ;;
		--) shift; break ;;
		*) die "invalid option: '$1'." ;;
	esac
	shift
done

# Get the ids of new texts
ids="$( mmcli -m "$modem" --messaging-list-sms |
	grep -Eo '/SMS/[0-9]+ \(received\)' | grep -Eo '[0-9]+' )"

count="$(echo "$ids" | deleteEmptyLines | wc -l)"

[ "$count" -eq 0 ] && exit

echo "$ids" | while read -r id; do
	# Get the details of the message
	details="$(mmcli -m "$modem" -s "$id" -K)"
	number="$(echo "$details" | grep "sms.content.number" | cut -d':' -f2- |
		trimWhitespace)"
	text="$(echo "$details" | grep "sms.content.text" | cut -d':' -f2- |
		trimWhitespace)"
	time="$(echo "$details" | grep "sms.properties.timestamp" | cut -d':' -f2- |
		trimWhitespace)"

	# Make a directory if necesary
	mkdir -p "$SMS_DIR/$number"

	log="$SMS_DIR/$number/sms.log"

	[ ! -f "$log" ] && printf '\00READ\00' >> "$log"

	# Store the message in the log file
	echo "RECIEVED"
	echo "SENDER: $number" >> "$log"
	echo "TIME: $(date -d "$time")" >> "$log"
	echo "----" >> "$log"
	echo -e "$text" >> "$log"
	printf '\00\n' >> "$log"

	mmcli -m "$modem" --messaging-delete-sms="$id"
done

echo "$count new messages"
