#!/usr/bin/env python
"""
send_email_to_galaxy_users.py

Created by Anne Pajon on 09 Feb 2012
Copyright (c) 2012 Cancer Research UK - Cambridge Research Institute. All rights reserved.

Script for sending email to Galaxy users

"""

import argparse
import logging

import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

from sqlalchemy import create_engine

# smtp server
CRUKCI_SMTP = 'mailrelay.cruk.cam.ac.uk'
INTERNAL_CRUKCI_SMTP = 'smtp.cruk.cam.ac.uk'


def send_email(send_to, username, subject, internal_smtp):

    send_from = 'anne.pajon@cruk.cam.ac.uk'

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = send_from
    msg['To'] = send_to

    if send_to.endswith('@cruk.cam.ac.uk'):
        extra = ""
    else:
        extra = """To migrate your current account in Galaxy, please log in as usual and change your current email address from %s to a cruk.cam.ac.uk one otherwise you will not be able to log in after Friday 16th October 2015.

""" % send_to

    msg.attach(MIMEText("""Dear Galaxy User,

Our Galaxy production server at http://galaxy.cruk.cam.ac.uk/ is now using the CRUK-CI authentication system.

%sIt means that from now on you will be able to use your cruk.cam.ac.uk email address and password to log in into Galaxy.

In preparation to the integration of our cluster with Galaxy, please do make sure that your username recorded in Galaxy which is currently '%s' is the username you use here at CRUK-CI.

To change your username in Galaxy, first log in then click on the dark blue top menu on 'User' > 'Preferences' > 'Manage your information' and changed your public name.

If you have any questions or if you request any further information, please do not hesitate to contact me.

Kind regards,
Anne.
--
Dr Anne Pajon - Bioinformatics Core
Cancer Research UK - Cambridge Institute
Li Ka Shing Centre, Robinson Way, Cambridge CB2 0RE
anne.pajon@cruk.cam.ac.uk | +44 (0)1223 769 631
""" % (extra, username)))

    try:
        if internal_smtp:
            mail = smtplib.SMTP(INTERNAL_CRUKCI_SMTP)
        else:
            mail = smtplib.SMTP(CRUKCI_SMTP)
        mail.sendmail(send_from, [send_to], msg.as_string())
        mail.quit()
    except Exception:
        print "%s" % (msg.as_string())
        raise


def main():
    # logging configuration
    logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)

    # get the options
    parser = argparse.ArgumentParser()
    parser.add_argument("--db", dest="connection", action="store", help="Galaxy database connection e.g. postgres://galaxy:galaxy@localhost:5432/galaxy", required=True)
    parser.add_argument("--internal", dest="intsmtp", action="store_true", default=False, help="Use the internal smtp server to only send email within the institute")
    parser.add_argument("--email", dest="email", action="store_true", default=False, help="Send email to users")
    options = parser.parse_args()

    engine = create_engine(options.connection, echo=False)
    connection = engine.connect()
    users = connection.execute("""
    SELECT *
    FROM galaxy_user
    """)
    for user in users:
        email = user['email']
        username = user['username']
        logging.info("[email: %s, username: %s]" % (email, username))
        if email == 'anne.pajon@cruk.cam.ac.uk':
            logging.info("Sending email to %s" % email)
            send_email(email, username, 'Galaxy Server - ACTION REQUIRED - New Authentication System', options.intsmtp)
        if options.email:
            if email.endswith('@cancer.org.uk'):
                email.replace('@cancer.org.uk', '@cruk.cam.ac.uk')
                logging.info("Sending email to %s" % email)
                #send_email(email, username, 'Galaxy Server - ACTION REQUIRED - New Authentication System', options.intsmtp)


if __name__ == '__main__':
    main()

