#!/bin/bash
# {%- set MANAGERIP = salt['pillar.get']('global:managerip', '') %}
# {%- set THEHIVEUSER = salt['pillar.get']('global:hiveuser', 'hiveadmin') %}
# {%- set THEHIVEPASSWORD = salt['pillar.get']('global:hivepassword', 'hivechangeme') %}
# {%- set THEHIVEKEY = salt['pillar.get']('global:hivekey', '') %}

. /usr/sbin/so-common

thehive_clean(){
    sed -i '/^  hiveuser:/d' /opt/so/saltstack/local/pillar/global.sls
    sed -i '/^  hivepassword:/d' /opt/so/saltstack/local/pillar/global.sls 
}

thehive_init(){
    THEHIVE_URL="http://{{MANAGERIP}}:9000/thehive/"
    THEHIVE_API_URL="${THEHIVE_URL}api"
    THEHIVE_USER="{{THEHIVEUSER}}"
    THEHIVE_PASSWORD="{{THEHIVEPASSWORD}}"
    THEHIVE_KEY="{{THEHIVEKEY}}"
    SOCTOPUS_CONFIG="/opt/so/saltstack/salt/soctopus/files/SOCtopus.conf"

    echo -n "Waiting for TheHive..."
    if wait_for_web_response $THEHIVE_URL "TheHive" 120; then
        # Migrate DB
        curl -sk -XPOST -L "$THEHIVE_API_URL/maintenance/migrate"

        # Create intial TheHive user
        curl -sk -L "$THEHIVE_API_URL/user" -H "Content-Type: application/json" -d "{\"login\" : \"$THEHIVE_USER\",\"name\" : \"$THEHIVE_USER\",\"roles\" : [\"read\",\"alert\",\"write\",\"admin\"],\"preferences\" : \"{}\",\"password\" : \"$THEHIVE_PASSWORD\", \"key\": \"$THEHIVE_KEY\"}"
   
        # Pre-load custom fields
        #
        # reputation
        curl -sk -L "$THEHIVE_API_URL/list/custom_fields" -H "Authorization: Bearer $THEHIVE_KEY" -H "Content-Type: application/json" -d "{\"value\":{\"name\": \"reputation\", \"reference\": \"reputation\", \"description\": \"This field provides an overall reputation status for an address/domain.\", \"type\": \"string\", \"options\": []}}"
   
        touch /opt/so/state/thehive.txt
    else
        echo "We experienced an issue connecting to TheHive!"
        exit 1
    fi
}

if [ -f /opt/so/state/thehive.txt ]; then
    thehive_clean
    exit 0
else
    if wait_for_web_response http://{{MANAGERIP}}:9400/_cluster/health '"status":"green"' 120; then
        thehive_init
        thehive_clean
    else
        echo "TheHive Elasticsearch server is not ready; unable to proceed with TheHive init."
        exit 1
    fi
fi
