#!/bin/bash

EXISTING_MAILING_LISTS="/etc/perun/services/mailman_mu/existing_mailinglists"
NOTIF_MAIL="notify@example.com" # Where to send the notification about request to change the mailing list
FROM_PERUN_DIR="${WORK_DIR}/mailinglists/"
PERUN_MAIL="perun@example.com" # Mail address which is used in notification as a signature

### Status codes
I_MAIL_SENT=(0 'Request for mailing list ${MAILING_LIST_NAME} owner has been sent to ${NOTIF_MAIL}.')

### Error codes
E_MAILING_LISTS_NOT_EXISTS=(10 'Cannot change owner of the mailing list: ${MAILING_LIST_NAME} does not exists.')

# Check if the file with Perun managed mailing lists exists
catch_error E_EXISTING_MAILING_LISTS_NOT_EXISTS stat ${EXISTING_MAILING_LISTS} >/dev/null

for MAILING_LIST_NAME in `ls $FROM_PERUN_DIR/` ; do
        if [ `grep -c "^${MAILING_LIST_NAME} " ${EXISTING_MAILING_LISTS}` -eq 0 ]; then
                log_msg E_MAILING_LISTS_NOT_EXISTS
        else
                # Get mailing list admin's mail
                MAILING_LIST_ADMIN=`grep MANAGERS_MAIL $FROM_PERUN_DIR/$MAILING_LIST_NAME | sed 's/^#MANAGERS_MAIL=\(.*\)$/\1/'`

                # Extract mailing list owner from current mailman configuration
                MAILMAN_MAILING_LIST_OWNER=`grep "^${MAILING_LIST_NAME}" ${EXISTING_MAILING_LISTS} | awk '{ print $3; }'`

                if [ "${MAILMAN_MAILING_LIST_OWNER}" != "${MAILING_LIST_ADMIN}" ]; then
                        # Prepare message
                        MSG="Request to change the manager of the mailing list:\n\nMAILING LIST NAME: ${MAILING_LIST_NAME}\nNEW MAILING LIST MANAGER: ${MAILING_LIST_ADMIN}\n\nYour Perun System\n--\n${PERUN_MAIL}"

                        # Send mail
                        echo -e ${MSG} | mail -s "[Perun] Request to change the manager of mailing list '${MAILING_LIST_NAME}'" ${NOTIF_MAIL}

                        log_msg I_MAIL_SENT
                fi
        fi
done
