#!/bin/bash
#
# Script for adding SMTP credentials in the OpenSearch keystore. Runs the
# directives on every OpenSearch node as of the current docker-compose.yml

set -euo pipefail

if [[ ! -f ".env" ]]; then
    echo >&2 "[ERROR] The script needs to be executed from the project directory!"
    exit 1
fi

read -p "Enter the name of your STMP sender: " smtp_sender_name

# SMTP sender name must not be empty
if [ -z "$smtp_sender_name" ]; then
    echo >&2 "[ERROR] STMP sender name can not be empty."
    exit 1
fi

# import to node 1
docker compose exec os-node-1 ./bin/opensearch-keystore add "plugins.alerting.destination.email.${smtp_sender_name}.username"
docker compose exec os-node-1 ./bin/opensearch-keystore add "plugins.alerting.destination.email.${smtp_sender_name}.password"
echo "[INFO] Imported SMTP Credentials to OpenSearch node-1 keystore."

# import to node 2
docker compose exec os-node-2 ./bin/opensearch-keystore add "plugins.alerting.destination.email.${smtp_sender_name}.username"
docker compose exec os-node-2 ./bin/opensearch-keystore add "plugins.alerting.destination.email.${smtp_sender_name}.password"
echo "[INFO] Imported SMTP Credentials to OpenSearch node-2 keystore."

# get credentials from .env for authentication with OpenSearch
username=$(grep -E "^OPENSEARCH_ADMIN_USERNAME=" .env | cut -d '=' -f 2- || echo "admin")
password=$(grep -E "^OPENSEARCH_ADMIN_PASSWORD=" .env | cut -d '=' -f 2- || echo "admin")

# reload settings for changes to take effect
response=$(docker compose exec os-node-1 curl -s \
    -u "${username}:${password}" \
    -w "\n%{http_code}" \
    -X POST https://localhost:9200/_nodes/reload_secure_settings \
    --cacert /usr/share/opensearch/config/root-ca.pem)

# separate response message and HTTP status code
response_message=$(echo "$response" | sed '$d')
http_status=$(echo "$response" | tail -n1)

echo "[INFO] Response Message: $response_message"

if [ "$http_status" -eq 200 ]; then
    echo "[INFO] Reloaded secure settings, STMP Credentials were added successfully."
else
    echo >&2 "[ERROR] Request failed with HTTP status code: $http_status"
    exit 1
fi