#!/bin/bash

# Author: Tomi Eckert
# This script helps to configure monitor.conf

# Source the monitor.conf to get current values
source monitor.conf

# Check if COMPANY_NAME or NTFY_TOKEN are still default
if [ "$COMPANY_NAME" = "Company" ] || [ "$NTFY_TOKEN" = "tk_xxxxx" ]; then
    echo "Default COMPANY_NAME or NTFY_TOKEN detected. Running configuration..."
else
    echo "COMPANY_NAME and NTFY_TOKEN are already configured. Exiting."
    exit 0
fi

# Prompt for COMPANY_NAME
read -p "Enter Company Name (e.g., MyCompany): " COMPANY_NAME_INPUT
COMPANY_NAME_INPUT=${COMPANY_NAME_INPUT:-"$COMPANY_NAME"} # Default to current value if not provided

# Prompt for NTFY_TOKEN
read -p "Enter ntfy.sh token (e.g., tk_xxxxx): " NTFY_TOKEN_INPUT
NTFY_TOKEN_INPUT=${NTFY_TOKEN_INPUT:-"$NTFY_TOKEN"} # Default to current value if not provided

# Define HANA client paths
HDB_CLIENT_PATH="/usr/sap/hdbclient"
HDB_USERSTORE_EXEC="${HDB_CLIENT_PATH}/hdbuserstore"

# List HANA user keys and prompt for selection
echo "Available HANA User Keys:"
HANA_KEYS=$("$HDB_USERSTORE_EXEC" list 2>/dev/null | tail -n +3 | grep '^KEY ' | awk '{print $2}')
if [ -z "$HANA_KEYS" ]; then
    echo "No HANA user keys found. Please create one using keymanager.sh or enter manually."
    read -p "Enter HANA User Key (e.g., CRONKEY): " HANA_USER_KEY_INPUT
else
    echo "$HANA_KEYS"
    read -p "Enter HANA User Key from the list above (e.g., CRONKEY): " HANA_USER_KEY_INPUT
fi
HANA_USER_KEY_INPUT=${HANA_USER_KEY_INPUT:-"CRONKEY"} # Default value

# Find paths for sapcontrol and hdbsql
SAPCONTROL_PATH_INPUT=$(which sapcontrol)
HDBSQL_PATH_INPUT=$(which hdbsql)

# Default values if not found
SAPCONTROL_PATH_INPUT=${SAPCONTROL_PATH_INPUT:-"/usr/sap/NDB/HDB00/exe/sapcontrol"}
HDBSQL_PATH_INPUT=${HDBSQL_PATH_INPUT:-"/usr/sap/hdbclient/hdbsql"}

# Update monitor.conf
sed -i "s/^COMPANY_NAME=\".*\"/COMPANY_NAME=\"$COMPANY_NAME_INPUT\"/" monitor.conf
sed -i "s/^NTFY_TOKEN=\".*\"/NTFY_TOKEN=\"$NTFY_TOKEN_INPUT\"/" monitor.conf
sed -i "s#^SAPCONTROL_PATH=\".*\"#SAPCONTROL_PATH=\"$SAPCONTROL_PATH_INPUT\"#" monitor.conf
sed -i "s#^HDBSQL_PATH=\".*\"#HDBSQL_PATH=\"$HDBSQL_PATH_INPUT\"#" monitor.conf
sed -i "s/^HANA_USER_KEY=\".*\"/HANA_USER_KEY=\"$HANA_USER_KEY_INPUT\"/" monitor.conf

echo "monitor.conf updated successfully!"