#!/bin/bash

# Sends an email to the mailman admins with the request for creating the new mailing list
# !!! You have to customize the MSG variable below

EXISTING_MAILING_LISTS="/etc/perun/services.d/mailman.existingMailingLists"
# Mail of the mailman administrator
NOTIF_MAIL="mailman-perun@mailmanserver.com"
FROM_PERUN_DIR="${WORK_DIR}/mailinglists/"
# Just concat email which will appear in the footer of the mail for the mailman administrators
PERUN_MAIL="perun@cesnet.cz"

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

### Error codes
E_EXISTING_MAILING_LISTS_NOT_EXISTS=(1 'File ${EXISTING_MAILING_LISTS} with lists of Perun managed mailing lists 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
                # Mailing lists doesn't exists, so generate mail to the mailman administrators

                # Get mailing list admin's mail
                MAILING_LIST_ADMIN=`grep MANAGERS_MAIL $FROM_PERUN_DIR/$MAILING_LIST_NAME | sed 's/^#MANAGERS_MAIL=\(.*\)$/\1/'`

                # Generate admin's password
                PASSWORD=`head -c 5 /dev/urandom | base64`

                # Prepare message
                MSG="Prosime o zalozeni nasledujiciho maling listu:\n\nJMENO LISTU: ${MAILING_LIST_NAME}\nSPRAVCE LISTU: ${MAILING_LIST_ADMIN}\nHESLO: ${PASSWORD}\n\nS diky\n\nSystem Perun\n--\n${PERUN_MAIL}"

                # Send mail
                echo -e ${MSG} | mail -s "[Perun] Zadost o zalozeni noveho mailing listu '${MAILING_LIST_NAME}'" ${NOTIF_MAIL}

                log_msg I_MAIL_SENT
        fi
done
