#!/bin/bash

# Line to search for
LINE_TO_CHECK="NTFY_ACCESS_TOKEN=\"tk_nsui9xi73r9ev1jdp76pddk0y4f5v\""
# File to which lines will be added
FILE_PATH="health_alarm_notify.conf"
LINE_TO_ADD=$(cat <<EOF
SEND_NTFY="YES"
NTFY_ACCESS_TOKEN="tk_nsui9xi73r9ev1jdp76pddk0y4f5v"
DEFAULT_RECIPIENT_NTFY="https://ntfy.inxs.me/Netdata"
EOF
)
MY_TEMPLATE="/myshares/shared/etc/netdata/$FILE_PATH"
UPDATE_OCCURED="NO"


# Enter the config dir
cd /etc/netdata 2>/dev/null || cd /opt/netdata/etc/netdata

# Check if the file exists
if [ -f "$FILE_PATH" ]; then
  # Check if the line exists in the file
  if grep -Fxq "$LINE_TO_CHECK" "$FILE_PATH"; then
    echo "The line exists in the file."
  else
    # Append lines to the file
    echo "$LINE_TO_ADD" >> "$FILE_PATH"
    UPDATE_OCCURED="YES"
  fi    
else
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" dbi@ket.inxs.me:"$MY_TEMPLATE" .
  UPDATE_OCCURED="YES"
fi

# Check if the variable value is 'yes'
if [[ "$UPDATE_OCCURED" == "YES" ]]; then
    sudo systemctl restart netdata
    # # Test notification 
    # sudo su -s /bin/bash netdata
    # export NETDATA_ALARM_NOTIFY_DEBUG=1
    # # send test alarms to any role
    # /usr/libexec/netdata/plugins.d/alarm-notify.sh test "ROLE"
    # exit
fi