#!/bin/bash
# info: add user notification
# options: USER TOPIC NOTICE [TYPE]
#
# This function adds a new user notification to the panel.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
user=$1
topic=$(echo "$2" | sed "s/'/%quote%/g")
type=$4
priority=$5

# Includes
# shellcheck source=/etc/tuliocp/tulio.conf
source /etc/tuliocp/tulio.conf
# shellcheck source=/usr/local/tulio/func/main.sh
source $TULIO/func/main.sh
# load config file
source_conf "$TULIO/conf/tulio.conf"

# NOTICE is rendered client-side as raw HTML, so it's run through an
# allow-list sanitizer before anything else touches it.
notice=$("$TULIO_PHP" "$TULIO/func/internal/sanitize_html.php" "$3" | sed "s/'/%quote%/g")

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '2' "$#" 'USER TOPIC NOTICE TYPE [PRIORITY]'
is_format_valid 'user' 'topic' 'notice' 'priority'
is_object_valid 'user' 'USER' "$user"
is_common_format_valid "$type"

# Perform verification if read-only mode is enabled
check_tulio_demo_mode

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Defining notification id
if [ -e "$USER_DATA/notifications.conf" ]; then
	nid=$(grep "NID=" $USER_DATA/notifications.conf | cut -f 2 -d \')
	nid=$(echo "$nid" | sort -n | tail -n1)
	if [ -n "$nid" ]; then
		nid="$((nid + 1))"
	else
		nid=1
	fi
else
	nid=1
fi

# Generating timestamp
time_n_date=$(date +'%T %F')
time=$(echo "$time_n_date" | cut -f 1 -d \ )
date=$(echo "$time_n_date" | cut -f 2 -d \ )

# Concatenating string
str="NID='$nid' TOPIC='$topic' NOTICE='$notice' TYPE='$type' PRIORITY='$priority'"
str="$str ACK='no' TIME='$time' DATE='$date'"

# Adding to config
echo "$str" >> $USER_DATA/notifications.conf

# Changing permissions
chmod 660 $USER_DATA/notifications.conf

#----------------------------------------------------------#
#                       Tulio                             #
#----------------------------------------------------------#

# Updating notification counter
if [ -z "$(grep NOTIFICATIONS $USER_DATA/user.conf)" ]; then
	sed -i "s/^TIME/NOTIFICATIONS='yes'\nTIME/g" $USER_DATA/user.conf
else
	update_user_value "$user" '$NOTIFICATIONS' "yes"
fi

exit
