#!/bin/bash
# simple script to send/push messages to a gotify instance using curl
set -aeou pipefail

GOTIFY_CLI_CONFIG_FILE="${GOTIFY_CLI_CONFIG_FILE-"$HOME/.gotify.sh"}"
GOTIFY_STDIN=false


function printHelp(){
    cat << EOF
Usage ${0##*/} [options..] <Mesage>
-h,-?, --help           Show help and exit
-t,--title              Set title of message
-p,--priority           Set priority of the message
-T,--token              Specify gotify app token
-b,--bash-completion    Print out bash completion and exit
-s, --stdin             Read STDIN instead of taking <message>
EOF
}

function print_bash_completion(){
    cat << EOF
GOTIFY_CLI_COMPLETE="\\
    -h\\
    -t\\
    -p\\
    -T\\
    -b\\
    --help\\
    --title\\
    --token\\
    --bash-completion"

_gotify_cli_complete()
{
  local cur suggestions
  cur="\${COMP_WORDS[COMP_CWORD]}"
  suggestions="\$GOTIFY_CLI_COMPLETE"
  COMPREPLY=( \$(compgen -W "\${suggestions}" -- \${cur}) )
  return 0
}
complete -F _gotify_cli_complete ${0##*/}
EOF
}

function sendMessage(){
    local PRIORITY="${GOTIFY_PRIORITY:-5}"
    local TITLE="${GOTIFY_TITLE:-"gotify-cli"}"
    local TOKEN="${GOTIFY_TOKEN:-"xxxxxxxx"}"
    local URL="${GOTIFY_URL:-"http://localhost"}"

    if ! command -v curl &> /dev/null; then
        printf "ERROR: curl not found\n"
        return 4
    fi

    curl "$URL/message?token=$TOKEN" -F "title=$TITLE" -F "priority=$PRIORITY" -F "message=$1"
}

if [[ -f "$GOTIFY_CLI_CONFIG_FILE" ]];then
    # shellcheck disable=1090
    source "$GOTIFY_CLI_CONFIG_FILE"
fi

while :; do
    case "${1-}" in
        -h|-\?|--help)
            printHelp
            exit
            ;;
        -p|--priority)
            GOTIFY_PRIORITY="$2"
            shift
            ;;
        -t|--title)
            GOTIFY_TITLE="$2"
            shift
            ;;
        -T|--token)
            GOTIFY_TOKEN="$2"
            shift
            ;;
        -u|--url)
            GOTIFY_URL="$2"
            shift
            ;;
        -s|--stdin)
            GOTIFY_STDIN=true
            ;;
        -b|--bash-completion)
            print_bash_completion
            exit 0
            ;;
        --)                 #End of all options
            shift
            break
            ;;
        -?*)
            printf "'%s' is not a valid option\n" "$1" >&2
            exit 1
            ;;
        *)                 #Break out of case, no more options
            break
    esac
    shift
done

if $GOTIFY_STDIN; then
    read -r MESSAGE
elif [[ -z "${1-}" ]]; then
    printf "ERROR: No message to send\n" >&2
    printHelp
    exit 2
else
    MESSAGE="$1"
fi

sendMessage "$MESSAGE"