#!/bin/bash
# Pagerduty Integration
#
# Copyright (C) 2015, Wazuh Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Author: Daniel B. Cid
# Modified by: @spartantri
# Last modified: Jan 18, 2019

ALERTFILE=$1
APIKEY=$2
WEBHOOK=$3

LOCAL=`dirname $0`;
SERVER=`hostname`
cd $LOCAL
cd ../
PWD=`pwd`


build_payload () {
    #echo 'payload={"username":"OSSEC2slack Integration from '$alertlocation'", "icon_emoji": ":ghost:", "text": "OSSEC Alert\n```'$alertdate $alertlocation'\nRule:'$ruleid' (level '$alertlevel'): '$ruledescription'\nIP:'$srcip'\n'$alertlog'\n```"}' > $postfile
    payload="{\"service_key\": \"$APIKEY\", \"incident_key\": \"Alert: '$alertdate' / Rule: '$ruleid'\", \"event_type\": \"trigger\", \"description\": \"Wazuh Alert: '$ruledescription'\", \"client\": \"Wazuh\", \"client_url\": \"http://127.0.0.1:5601/app/wazuh\", \"details\": { \"location\": \"'$alertlocation'\", \"Rule\":\"'$ruleid'\", \"Description\":\"'$ruledescription'\", \"Log\": \"'$alertlog'\" } }";

}

send_payload () {

        postfile=`mktemp`
        echo $payload > $postfile

        if [ ! $? = 0 ]; then
            echo "Cannot write temporary alert file to `pwd`"
            exit 1;
        fi

        # Echo payload
        #echo  -n "-------\nSending:\n${payload}\n"

        # Send the pagerduty notification
        curl -H "Content-type: application/json" -X POST --data "@$postfile" "$WEBHOOK"

        if [ ! $? = 0 ]; then
            echo "Error sending the alert to pagerduty"
            exit 1;
        fi

        rm -f $postfile;
}

# Logging the call
echo "`date` $0 $1 $2 $3" >> ${PWD}/logs/integrations.log
# Full log
#cat $1 >> ${PWD}/logs/integrations.log; echo -e "\n" >> ${PWD}/logs/integrations.log

# API key must be provided
if [ "x${APIKEY}" = "x" ]; then
   echo "$0: Missing argument <alertfile> <api_key> [webhook]"
   echo "Default webhook: https://events.pagerduty.com/generic/2010-04-15/create_event.json"
   exit 1;
fi

# webhook is optional, use default developer API if not specified
if [ "x${WEBHOOK}" = "x" ]; then
   WEBHOOK="https://events.pagerduty.com/generic/2010-04-15/create_event.json"
fi

# Checks if alert file is present and read all alerts present on the file
ls $ALERTFILE >/dev/null 2>&1
if [ ! $? = 0 ]; then
    echo "$0: Missing file: ${ALERTFILE}"
    exit 1;
else
    # This script can be also to send multiple alerts on a single file IF json format is used
    # Read the file and send alert per line found if format is json otherwise use text format
    while read line; do
        if [ ! "${line:0:1}" = "{" ]; then
            #echo "Alert is not in JSON format"
            alertformat="Not JSON"
            break
        fi
        #. $ALERTFILE
        if [ "x${alertlog}" = "x" ]; then
            alert=$line
            alertdate=`echo ${alert} |egrep -o 'timestamp":"[^"]+' |awk -F\" '{print $NF}'`
            ruleid=`echo ${alert} |egrep -o 'rule":{[^{]+"id":"[^"]+' |awk -F\" '{print $NF}'`
            alertlocation=`echo ${alert} |egrep -o 'location":"[^"]+' |awk -F\" '{print $NF}'`
            ruledescription=`echo ${alert} |egrep -o 'description":"[^"]+' |awk -F\" '{print $NF}'`
            alertlog=`echo ${alert} |egrep -o 'alertlog":{[^{]+"id":"[^"]+' |awk -F\" '{print $NF}'`
        fi

        build_payload
        send_payload

    done < $ALERTFILE

    # If the alert file was not in json format assume text format is in use
    if [ ! "x${alertformat}" = "x" ]; then
        #echo "Processing non-JSON alert"
        alert=`cat ${ALERTFILE}`
        while read line; do
            alertdate=`echo ${alert} |egrep -o "alertdate='[^']+" |awk -F\' '{print $NF}'`
            ruleid=`echo ${alert} |egrep -o "ruleid='[^']+" |awk -F\' '{print $NF}'`
            alertlocation=`echo ${alert} |egrep -o "alertlocation='[^']+" |awk -F\' '{print $NF}'`
            ruledescription=`echo ${alert} |egrep -o "ruledescription='[^']+" |awk -F\' '{print $NF}'`
            alertlog=`echo ${alert} |egrep -o "alertlog='[^']+" |awk -F\' '{print $NF}'`
        done < $ALERTFILE
        build_payload
        send_payload
    fi
fi

exit 0;
