#!/bin/sh

# sms.sh
# 2025-04-18
# by Gernot Walzl

# Sends personalized form text messages by replacing the some variables
# (NAME, OPENING, CLOSING) to a list of recipients using termux-sms-send.
# For termux-sms-send, the Android package com.termux.api version <= 0.31
# is required to be installed. SEND_SMS permission needs to be granted
# manually under Settings > Apps > Termux:API > Permissions.

# Example recipients.csv:
# John;+12345678;Hi John,;Regards, Joe

# Example message.txt:
# $OPENING how are you? $CLOSING

TO=${TO:-'recipients.csv'}
MSG=${MSG:-'message.txt'}
DELAY=${DELAY:-'15'}

if [ ! -r "$TO" ]; then
  echo 'Error: List of recipients not readable.'
  exit 1
fi
if [ ! -r "$MSG" ]; then
  echo 'Error: Message not readable.'
  exit 1
fi

cat "$MSG"
echo ''
while read -r RECIPIENT; do
  FIRST=$(echo "$RECIPIENT" | cut -c1)
  if [ "$FIRST" = "#" ]; then
    continue
  fi
  NAME=$(echo "$RECIPIENT" | cut -d';' -f1)
  NUMBER=$(echo "$RECIPIENT" | cut -d';' -f2)
  if [ -z "$NUMBER" ]; then
    continue
  fi
  OPENING=$(echo "$RECIPIENT" | cut -d';' -f3)
  CLOSING=$(echo "$RECIPIENT" | cut -d';' -f4)
  TEXT=$(sed -e "s/\$NAME/$NAME/g" \
             -e "s/\$OPENING/$OPENING/g" \
             -e "s/\$CLOSING/$CLOSING/g" \
             "$MSG")
  echo "to ${NAME} (${NUMBER}) in ${DELAY}s"
  sleep "$DELAY"
  termux-sms-send -n "$NUMBER" "$TEXT"
done < "$TO"