#!/opt/osstech/bin/python2.7
# encoding: utf-8

# googleapps-emaillist-csvadd: Email list create to Google Apps from CSV file
# Copyright (C) TAKEDA Yasuma @ Open Source Solution Technology Corp.
#
# License: GNU General Public License version 2 or later
# Date: 2008-10-21, since 2008-10-21

import gdata.apps.service
import os,sys,csv, string
import datetime
import osstech.apps.error
import osstech.apps.config

LOGFILE = "googleapps-emaillist-csvadd.log"
CONFFILE = "/opt/osstech/etc/googleapps-account.conf"

class opLog:
    def __init__(self, logdir):
        now = datetime.datetime.now()
        logdate = now.strftime("%Y%m%d-%H%M%S")
        self.logf = logdir + "/" + LOGFILE
        try:
            self.fd = open(self.logf, "a")
            self.fd.write("================================================\n")
            self.fd.write(logdate + " JST\n")
        except IOError, e:
            sys.stderr.write("Failed to open logfile [" + self.logf + "]\n")
            sys.exit(1)

    def write(self, messages):
        try:
            self.fd.write(messages)
            sys.stdout.write(messages)
        except IOError, e:
            sys.stderr.write("Failed to write log [" + messages + "]\n")

    def flush(self):
        self.fd.flush()


def usage():
    sys.stderr.write("Usage: " + sys.argv[0] + " <csvfile>\n")
    sys.exit(1)


def main():
    # Config file
    conf = osstech.apps.config.Config()
    conf.readconfig(CONFFILE)
    myLog = opLog(conf.logdir)
    service = None

    try:
        csvfile = sys.argv[1]
        reader = csv.reader(file(csvfile, 'r'))
    except IOError , e:
        myLog.write(csvfile + ":" + e.strerror + "\n")
        sys.exit(1)
    except IndexError:
        myLog.write("Error: CSV file is needed.\n")
        usage()
    except :
        myLog.write("Fail to read " + csvfile + "\n")
        sys.exit(1)

    try:
        service = gdata.apps.service.AppsService(conf.admin,conf.admin_pass,conf.domain)
        service.ProgrammaticLogin()
    except gdata.apps.service.AppsForYourDomainException , e:
        myLog.write("Fail to connect to Google. Errno: " + str(e.error_code) +"\n")
        sys.exit(1)
    except:
        myLog.write("service.ProgrammaticLogin(): Unexpected error\n")
        sys.exit(1)

    i = 0
    ml_success = 0
    u_success = 0
    ml_error = 0
    u_error = 0

    errstr = osstech.apps.error.Error()

    for row in reader:
        listname = ""
        noerror = True
        if i > 0 :
            n = 0
            for col in row:
                if n == 0:
                    # create email list
                    created = False
                    listname = col
                    try:
                        list = service.RetrieveEmailList(listname)
                    except gdata.apps.service.AppsForYourDomainException , e:
                        if e.error_code == 1301:
                            service.CreateEmailList(listname)
                            myLog.write("Success:Create " + listname + "\n")
                            ml_success = ml_success + 1
                        else:
                            myLog.write("Fail   :" + listname + ":" + errstr.str(e.error_code) + "\n")
                            ml_error = ml_error + 1
                    except:
                        myLog.write("Fail   :" + listname + ":unknown error\n")
                else:
                    recipient = col
                    # Email Listにユーザーを登録
                    try:
                        if string.find(col, '@') >= 0:
                            recipient = col
                        else:
                            recipient = col + "@" + conf.domain
                        service.AddRecipientToEmailList(recipient, listname)
                        u_success = u_success + 1
                        myLog.write("Success:"+ listname + ":" + recipient + " is added.\n")
                    except gdata.apps.service.AppsForYourDomainException, e:
                        myLog.write("Fail   :" + listname + ":" + recipient + ":" + e.reason + "\n")
                        u_error = u_error + 1
                    except:
                        myLog.write("Fail   :" + listname + ":" + recipient + ":unknown error\n")
                        
                n = n + 1
                # ここまでCSVの1行の処理


        myLog.flush()
        i=i+1

    myLog.write("\n")
    myLog.write((str(ml_success) + " mailing lists created.\n"))
    myLog.write(str(ml_error) + " mailing lists failed to create.\n")
    myLog.write((str(u_success) + " users added to mailing lists.\n"))
    myLog.write(str(u_error) + " users failed to add mailing lists.\n\n")
    sys.exit(0)

## run this script
main()
