#!/usr/bin/sh

set -e

RSPAMD_DB_DIR=${RSPAMD_DB_DIR:-"/var/lib/rspamd"}
RULES_FILE="${RSPAMD_DB_DIR}/rspamd.rules"
SCORES_FILE="${RSPAMD_DB_DIR}/rspamd.scores"

EMAIL_RULES_DIR=${EMAIL_RULES_DIR:-"/var/imunify360/files/email-rules"}

# define the directory with the last downloaded files
dir_name=$(ls -t1 ${EMAIL_RULES_DIR} | grep "v1_" | head -1)
dir_with_update=${EMAIL_RULES_DIR}/${dir_name}

if [ -z "${dir_name}" ]; then
  echo "failed to define directory name"
  exit 11
fi

cp ${dir_with_update}/* ${RSPAMD_DB_DIR}
chmod 644 ${RULES_FILE} ${SCORES_FILE}

systemctl is-active rspamd 1>/dev/null && systemctl reload rspamd

echo "$(date)    spamfilter rules and scores have been updated to:"
cat ${RSPAMD_DB_DIR}/description.json

# clean old archive if it exists
if [ -f "${RSPAMD_DB_DIR}/ie-rspamd-update.tgz" ]; then
  rm -f "${RSPAMD_DB_DIR}/ie-rspamd-update.tgz"
fi
