#!/bin/bash
#
# notify to slack
#

export PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin
export LANG=en_US.UTF-8
readonly CMDNAME=$(basename $0)
readonly CUR_DIR=$(cd $(dirname $0);pwd)
CONF_FILE=$CUR_DIR/$(basename $CMDNAME .sh).conf
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/****/****/****
SLACK_CHANNEL='#random'
SLACK_USERNAME='slack-webhook'

if [ -f "$CONF_FILE" ]; then
	source $CONF_FILE
fi

hello() {
	local slack_text="Hello"
	local attachments_text="
Hello world!
SCRIPT PATH: $HOSTNAME:$CUR_DIR/$CMDNAME
"
	local attachments_color="good"

	local body=$(slack_body "$SLACK_CHANNEL" "$SLACK_USERNAME" "$slack_text" "$attachments_text" "$attachments_color")
	slack_post "$SLACK_WEBHOOK_URL" "$body"
}

slack_body(){
	local channel="$1"
	local username=${2:-"slack-webhook"}
	local text="$3"
	local attachments_text="$4"
	local attachments_color="$5"
	# color code: https://api.slack.com/docs/attachments

	cat << EOS
{
  "channel": "$channel",
  "username": "$username",
  "text": "$text",
  "attachments": [
    {
      "color": "$attachments_color",
      "text": "$attachments_text"
    }
  ]
}
EOS
}

slack_post(){
	local url="$1"
	local body="$2"
	
	curl -s -S \
	     --retry 3 \
	     --retry-max-time 5 \
	     --max-time 5 \
	     -X POST "$url" \
	     -d "$body" 2>&1 >/dev/null | logger -i -t $CMDNAME

	if [ "$?" != "0" ]; then
		echo "slack_post() failed. url:$url body:$body" | logger -i -t $CMDNAME
	fi
}

main() {
	hello
}

usage_exit() {
    echo -e "Usage: $CMDNAME [OPTIONS]
  -h : help
" 1>&2
    exit 1
}

while getopts "h" OPT
do
  case $OPT in
    "h" )
        usage_exit
        ;;
    * )
        ;;
  esac
done
 
shift $(expr $OPTIND - 1)
 
main
