#!/bin/bash usage() { echo "usage: $(basename "$0") [-h host] [-p port] [-n nick] [-c context] [-u user] message" >&2 exit 2 } mkcommands() { local user="$1" local message="$2" local nick="$3" echo "NICK $nick" echo "USER $nick 8 * :notifirc bot" echo "PRIVMSG $user :$message" echo "QUIT" } mknick() { case "$context" in "") echo "$nick" ;; *) echo "$nick|$context" ;; esac } die() { local msg="fatal: $1" log "$msg" log "-----END *-----" echo "$msg" >&2 exit 3 } warn() { local msg="warning: $1" echo "$msg" >&2 log "$msg" } log_pipe() { local line while IFS= read line; do log "$line" done } log() { echo "$1" >>"$logfile" } load_defaults() { local rcfile=$1 test -e "$rcfile" || return 0 test -f "$rcfile" || { warn "defaults file is not a file: $rcfile" return 3 } test -r "$rcfile" || { warn "defaults file not readable: $rcfile" return 3 } bash -n "$rcfile" || { warn "syntax error in defaults file: $rcfile" return 3 } . "$rcfile" || { warn "error in defaults file: $rcfile" return 3 } } choose_logfile() { local path { echo /var/log/notifirc.log echo "$HOME/.notifirc.log" echo /tmp/notifirc.log } \ | while read path; do if test -w "$(dirname "$path")" \ || test -w "$path"; then echo "$path" break fi done } main() { local context nick host port user message logfile logfile=$(choose_logfile) test -n "$logfile" || { echo "could not find writable logfile location" >&2 echo "logging will be off!" >&2 logfile=/dev/null } load_defaults /etc/notifirc.rc load_defaults "$HOME/.notifirc.rc" while true; do case $1 in -c) context=$2; shift 2 || usage ;; -h) host=$2; shift 2 || usage ;; -n) nick=$2; shift 2 || usage ;; -p) port=$2; shift 2 || usage ;; -u) user=$2; shift 2 || usage ;; --) shift; break ;; -*) usage ;; *) break ;; esac done message="$*" test -n "$host" || usage test -n "$port" || usage test -n "$user" || usage test -n "$nick" || nick="notifirc" test -n "$message" || usage log "-----BEGIN sending notification-----" log "host='$host'" log "port='$port'" log "nick='$nick'" log "context='$context'" log "user='$user'" log "message='$message'" mkcommands "$user" "$message" "$(mknick)" \ | nc "$host" "$port" 2>&1 \ | log_pipe log "-----END sending notification-----" } main "$@"