#!/bin/sh

# Script to send push notifications via Pushover API
# Usage: pushover -m|--message <message> [-t|--title <title>] [-a|--attachment <attachment>]
# Requires PUSHOVER_APP_TOKEN and PUSHOVER_USER_TOKEN environment variables

if [ -z "$PUSHOVER_APP_TOKEN" ] || [ -z "$PUSHOVER_USER_TOKEN" ]; then
	echo "Error: Missing required environment variables"
	echo "Please set PUSHOVER_APP_TOKEN and PUSHOVER_USER_TOKEN"
	exit 1
fi

MESSAGE=""
TITLE=$HOSTNAME
ATTACHMENT=""

while [ $# -gt 0 ]; do
		case $1 in
				-m|--message)
						MESSAGE="$2"
						shift 2
						;;
				-t|--title)
						TITLE="$2"
						shift 2
						;;
				-a|--attachment)
						ATTACHMENT="$2"
						shift 2
						;;
				*)
						echo "Invalid option: $1"
						exit 1
						;;
		esac
done

if [ -z "$MESSAGE" ]; then
	echo "Error: Message is required"
	echo
	echo "Usage: pushover -m|--message <message> [-t|--title <title>] [-a|--attachment <attachment>]"
	echo "Options:"
	echo "  -m, --message <message>       Message text to send (required)"
	echo "  -t, --title <title>          Notification title (optional, defaults to hostname)"
	echo "  -a, --attachment <attachment> File to attach (optional, supports images, PDFs etc)"
	echo
	echo "Example:"
	echo "  pushover --message \"Backup complete\" --title \"Server Status\" --attachment /path/to/image.png"
	exit 1
fi

if [ -n "$ATTACHMENT" ]; then
  FILESIZE=$(stat -f%z "$ATTACHMENT" 2>/dev/null || stat -c%s "$ATTACHMENT" 2>/dev/null)
  if [ "$FILESIZE" -gt 5242880 ]; then
    echo "Error: Attachment size exceeds Pushover's 5MB limit"
    exit 1
  fi
fi

curl -s \
		--form-string "token=${PUSHOVER_APP_TOKEN}" \
		--form-string "user=${PUSHOVER_USER_TOKEN}" \
		--form-string "message=${MESSAGE}" \
		--form-string "title=${TITLE}" \
		${ATTACHMENT:+ -F "attachment=@$ATTACHMENT"} \
		https://api.pushover.net/1/messages.json
