#!/bin/sh
# This script send a text sms at the command line by creating
# a sms file in the outgoing queue.

# $1 is the destination phone number.
# $2 is the message text.
# If you leave $2 or both empty, the script will ask you.
# If you give more than 2 arguments, last is taken as a text and 
# all other are taken as destination numbers.
# If a destination is asked, you can type multiple numbers
# delimited with spaces.

smsd_user="_smsd"

# Will need echo which accepts -n argument:
ECHO=echo
case `uname` in
  SunOS)
    ECHO=/usr/ucb/echo
    ;;
esac

DEST=$1
TEXT=$2

if [ -z "$DEST" ]; then
  printf "Destination(s): "
  read DEST
  if [ -z "$DEST" ]; then
    echo "No destination, stopping."
    exit 1
  fi
fi

if [ -z "$TEXT" ]; then
  printf "Text: "
  read TEXT
  if [ -z "$TEXT" ]; then
    echo "No text, stopping."
    exit 1
  fi
fi

if [ $# -gt 2 ]; then
  n=$#
  while [ $n -gt 1 ]; do
    destinations="$destinations $1"
    shift
    n=`expr $n - 1`
  done
  TEXT=$1
else
  destinations=$DEST
fi

echo "Text: $TEXT"

for destination in $destinations
do
  echo "To: $destination"

  owner=""
  if [ -f /etc/passwd ]; then
    if grep $smsd_user: /etc/passwd >/dev/null; then
      owner=$smsd_user
    fi
  fi

  TMPFILE=`mktemp /tmp/smsd_XXXXXX`

  $ECHO "To: $destination" >> $TMPFILE
  $ECHO "" >> $TMPFILE
  $ECHO -n "$TEXT" >> $TMPFILE

  if [ "x$owner" != x ]; then
    chown $owner $TMPFILE
  fi

  FILE=`mktemp /var/spool/sms/outgoing/send_XXXXXX`
  mv $TMPFILE $FILE
done
