#!/bin/bash

export PATH="/bin:/sbin:/usr/bin:/usr/sbin"

DEBUG=1

FILE=$(basename $0).$$

/usr/bin/clear

cat <<EOF
===========================================================

This script will email the message you enter to all site 
administrators, site users, or both, for every domain 
hosted on this machine.

$(
    if [ "$DEBUG" = "1" ]
    then
        cat <<EOD
*NOTE*:  DEBUG mode is on, email will be displayed on-screen
         only.  Set DEBUG to 0 at the top of this script to
         have the email actually sent.
EOD
    
    fi
)

===========================================================

EOF


echo -n "Press <ENTER> to continue: "
read foo

TOLIST=""
TOADMINS=admins
TOCUSTOMERS=customers
TOSERVERCUSTOMERS=server_customers
CUSTOMERS_OF_CHOSEN_RESELLER=choose_reseller
TOBOTH=both

while [ -z "$TOLIST" ]
do

    clear
    cat <<EOF
===========================================================

Who will this email go to:
1)  Site administrators only
2)  Site customers only
3)  Both site administrators and customers
4)  Server customers only (non-reseller site owners and
    reseller account holders)
===========================================================

EOF

#5)  Customers of one or more resellers, with custom
#    From: address.
#

#    echo -n "Please enter 1, 2, 3, 4, or 5, then press <RETURN>: "
    echo -n "Please enter 1, 2, 3, or 4, then press <RETURN>: "
    read choice

    case $choice in
        1)  TOLIST=$TOADMINS;;
        2)  TOLIST=$TOCUSTOMERS;;
        3)  TOLIST=$TOBOTH;;
        4)  TOLIST=$TOSERVERCUSTOMERS;;
        *)  echo "Invalid choice: $choice";sleep 2;;
    esac
        #5)  TOLIST=$CUSTOMERS_OF_CHOSEN_RESELLER;;


done

USESITEADMIN=""

case $TOLIST in
    $TOADMINS|$TOBOTH|$TOSERVERCUSTOMERS)
        while [ -z "$USESITEADMIN" ]
        do
            clear
            cat <<EOF
===========================================================

Do you wish me to use the email addresses the site
administrators entered in the site admin preference
page of the Ensim GUI or their Ensim usernames for
this email?

1)  Use site administrator preference email address
2)  Use Ensim user name @ domain (e.g. admin@virthost.com)
 
===========================================================

EOF
            echo -n "Enter 1 or 2, then press <RETURN>: "
            read choice

            case $choice in
                1)  USESITEADMIN=0;;
                2)  USESITEADMIN=1;;
                *)  echo "Invalid choice: $choice";sleep 2; clear;;
            esac

        done

    ;;

esac

CHOSEN_RESELLERS=""
FROM_ADDRES

if [ $TOLIST = $CUSTOMERS_OF_CHOSEN_RESELLER ]
then
    
    while [ -z "$CHOSEN_RESELLERS" ]
    do
        clear
        cat <<EOF
===========================================================

Please select the resellers to whose customers I should
send email.  Enter more than one number with spaces
in between, e.g. 

1 4 5

Then press ENTER.
 
===========================================================

EOF
            echo -n "Enter 1 or 2, then press <RETURN>: "
            read choice

            case $choice in
                1)  USESITEADMIN=0;;
                2)  USESITEADMIN=1;;
                *)  echo "Invalid choice: $choice";sleep 2; clear;;
            esac

    done

    clear

    while [ -z "$FROM_ADDRESS" ]
    do
        clear
        cat <<EOF
===========================================================

Please enter the address you would like to be used in
the From: field of this email.  If you want to use the
server administrators' address, enter the word 

ADMIN

Press ENTER after you have entered the address you would
like to use.

===========================================================

EOF

        read ANS

        case $ANS in
            ADMIN) break;;
                *) FROM_ADDRESS=$(echo "$ANS" | sed -e 's/^  *//' -e 's/  *$//');;
        esac
                  
    done

fi

SEND_STYLE=0
USETO=1
USEBCC=2
EMAIL_ONE_AT_A_TIME=3

if [ ! -z "$FROM_ADDRESS" ]
then
    ADMIN="$FROM_ADDRESS"
else
    ADMIN=$(cat /etc/appliance/appliance.ini | fgrep admine | sed -e 's/.* = //')
fi

while [ $SEND_STYLE = 0 ]
do
    clear
    cat <<EOF

===========================================================

Please select how I should address and send out emails.

1)  Put all recipients in the To: line of the email.  Every
    recipient will be able to see every other recipient you
    are sending to.
2)  Put all recipients in the Bcc: line of the email.  The
    To: line will contain $ADMIN.  Recipients will
    not be able to see each other in the email.
3)  Send the email to a single recipient at the time
    (Slowest method).  The To: line will contain a
    single recipient.

===========================================================
    
EOF

    echo -n "Please enter 1, 2, or 3> "
    read ANS

    case $ANS in
        $USETO|$USEBCC|$EMAIL_ONE_AT_A_TIME) SEND_STYLE=$ANS;;
        *) echo "Invalid response: $ANS; please try again";sleep 2;;
    esac

done

while [ -z "$SUBJECT" ]
do
    clear
    cat <<EOF

===========================================================

Please enter a subject for this email, then press <ENTER>
to continue.

===========================================================

EOF

    echo -n "subject?> "
    read SUBJECT

done

SUBJECT="${SUBJECT:?Need subject for email!}"

while [ ! -s "$FILE" ]
do
    clear
    cat <<EOF

====================================================================

Enter the text of your email in pico.  When you are done creating
your email, press <Ctrl>-X to save and exit.

I will then email your message.

====================================================================

EOF

    echo -n "Press <RETURN> to start pico session: "
    read foo

    /usr/bin/pico -t -d $FILE

done

case $TOLIST in
    $TOADMINS|$TOBOTH|$TOSERVERCUSTOMERS)
        echo "Gathering site admin email addresses"
        
        for info in /home/virtual/*/info/current/siteinfo
        do
        
            #  Skip customers that are owned by reseller accounts
            if [ $TOLIST = $TOSERVERCUSTOMERS ]
            then
                resell=${info/siteinfo/reseller}
                if ! fgrep -q 'reseller_id = 0' $resell
                then
                    continue
                fi
            fi

            echo -n .
            DOMAIN=$(egrep '^domain' $info | sed -e 's/^.* = //')
            ADMIN_USER=$(egrep '^admin_user' $info | sed -e 's/^.* = //')
            NAME="$(fgrep $ADMIN_USER /home/virtual/$DOMAIN/etc/passwd | \
                   awk -F: '{print $5}')"
        
            if [ "$USESITEADMIN" = "0" ]
            then
                EMAIL=$(egrep '^email' $info | sed -e 's/^.* = //')
                EMAILS="$EMAILS \"$NAME\" <$EMAIL>,"
            else
                EMAILS="$EMAILS \"$NAME\" <$ADMIN_USER@$DOMAIN>,"
            fi
            
        done
    
        echo Done.
    ;;
esac

case $TOLIST in
    $TOCUSTOMERS|$TOBOTH)

        echo -n "Gathering customer emails for all domains: "

        CUSTOMERS="$(
            for domain in $(/usr/local/bin/sitelookup -a domain)
            do
                pass=/home/virtual/$domain/etc/passwd

                perl -n -e '@line = split(qq-:-, $_);
                            print qq-"$line[4]" <$line[0]- .
                            q+@'"$domain"'>, + if $line[2] > 1000;' $pass
            done
        )"

        echo done.

        CUSTOMERS="$(echo $CUSTOMERS | sed -e 's/^  *//')"
        EMAILS="${EMAILS}${CUSTOMERS}"

    ;;
esac

case $TOLIST in
    $TOSERVERCUSTOMERS)

        echo -n "Gathering reseller account holder emails: "

        if [ -x /usr/bin/python2.1 ]
        then
            PYTHON=/usr/bin/python2.1
        else
            PYTHON=/usr/bin/python2.2  #  3.5
        fi

        CUSTOMERS=$($PYTHON -c "
from vh3.modules import reseller

emails = []

for r in reseller.get_reseller_list():
    if r['fullname'] != None:
        if r['email'] != \"\":
            emails.append(\" \\\"%s\\\" <%s>\" % (r['fullname'], r['email']))
    
print ','.join(emails)
")

        CUSTOMERS="$(echo $CUSTOMERS | sed -e 's/^  *//')"
        EMAILS="${EMAILS}${CUSTOMERS}"

    ;;
esac

EMAILS="$(echo $EMAILS | sed -e 's/^  *//')"
EMAILS="$(echo $EMAILS | sed -e 's/,$//')"

echo "Sending mail"

CMD="/usr/sbin/sendmail -t -oi"

if [ "$DEBUG" = "1" ]
then
    CMD=less
fi

TO=""
BCC="Bcc: "

CONTENTS="$(cat $FILE)"

send_mail() {

    cat <<EOF | $CMD
From: "Administrator" <$ADMIN>
To: $TO
$BCC
Subject: $SUBJECT

$CONTENTS

EOF

}

case $SEND_STYLE in
    $USETO)
        TO="$EMAILS"
        send_mail
    ;;
    $USEBCC)
        TO="$ADMIN"
        BCC="Bcc: $EMAILS"
        send_mail
    ;;
    $EMAIL_ONE_AT_A_TIME)
         
        OCMD=cat

        if [ "$DEBUG" = "1" ]
        then
            CMD=cat
            OCMD=less
        fi

        echo $EMAILS | tr ',' '\012' | \
        while read name email
        do
            TO=$(echo "$name $email" | sed -e 's/^  *//' -e 's/  *$//')
            send_mail
        done | $OCMD

    ;;
    *) echo "Invalid send style $SEND_STYLE:  Bug!"; exit 1 ;;
esac

echo "Done."

rm $FILE

exit 0

