#!/usr/bin/python
# -*- coding: utf-8 -*-) 
#Anthony BERGER
#Envoie de sms par SFR DMC
#https://extranet.sfrbusinessteam.fr/extranet/cvg/accueil
#https://www.les800.com/e8ab/main.jsp?contrat=428020
#https://www.dmc.sfr-sh.fr/eDMC

from ftplib import FTP
import ftplib
import getopt
import sys
import os
import time
import tempfile

#DEFAULT PARAMS
verbose=0
tmp_dir='/tmp'
tmp_file=''
serviceid=''
spaceid=''
callplanningid=''
customizableid=''
scenarioid=''
mdp=''
pager=''
text=''
long=0
nsms=1

#init
dtime=int(time.time())
stime=time.strftime('%Y-%m-%d')

def debug(mess):
    """
    print message if verbose is 1
    """
    global verbose
    if verbose == 1:
        print mess

def usage():
    """
    print the usage
    """
    print """sms_dmc_sfr : send sms from DMC SFR

        sms_dmc_sfr [-h] [-s serviceId] [-e spaceId] [-a callPlanningId] [-c customizableId] [-o scenarioId] [-m password] [-p pager] [-t text_message] [-d dir] [-v] [-l] [-n]

        optional parameters:
        -h                                 print this message
        -v                                  verbose mode
        -d <dir>                       temp directory (default is /tmp)
        -l                                  use long sms (for message greater than 160 characters; message send by up to 25 sms [25*160=4000 characters]; be careful!; you should limite the number of sms )
        -n                                 max number of sms : implies -l option.
        
        mandatory parameters
        -s <serviceId>             serviceId
        -e <spaceId>              spaceId
        -a <callPlanningId>      callPlanningId
        -c <customizableId>    customizableId
        -o <scenarioId>             scenarioId
        -m <mdp>                    password
        -p <pager>                  pager number
        -t <message>              message to send
    """

def check_args():
    """
    use to verify the arguments passed to this script
    """
    global long
    global nsms
    
    try:
        o, a = getopt.getopt(sys.argv[1:], 'hvln:d:s:e:a:c:m:p:t:o:')
        opts = {}
    except getopt.GetoptError, err:
        print '\nERREUR : \n' + str(err)
        print '\nUSAGE :'
        usage()
        sys.exit(1)
        
    for k,v in o:
        opts[k] = v
    if  opts.has_key('-h'):
        usage(); sys.exit(0)
    if '-v' in opts:
        global verbose
        verbose = 1 
    if '-d'  in opts:
        global tmp_dir
        tmp_dir= opts['-d']
    if '-n' in opts:
        nsms=opts['-n']
        if int(nsms) > 25:           #text can not contain more than 4000 characters so 25 sms of 160 characters
            nsms=25
        debug("->init : long sms limited to " + str(nsms))
        if '-l' not in opts:
            debug("->init : -n option implies -l option")
            long=1
    if '-l' in opts:
        debug("->init : long sms")
        long=1
    if '-s'  not in opts:
        usage(); sys.exit(1)
    else :
        global serviceid
        serviceid = opts['-s']
    if '-e'  not in opts:
       usage(); sys.exit(1)
    else:
        global spaceid
        spaceid = opts['-e']
    if '-a'  not in opts:
       usage(); sys.exit(1)
    else:
        global callplanningid
        callplanningid = opts['-a']
    if '-c'  not in opts:
       usage(); sys.exit(1)
    else:
        global customizableid
        customizableid = opts['-c']
    if '-o'  not in opts:
       usage(); sys.exit(1)
    else:
        global scenarioid
        scenarioid = opts['-o']
    if '-m'  not in opts:
       usage(); sys.exit(1)
    else:
        global mdp
        mdp = opts['-m']
    if '-p'  not in opts:
       usage(); sys.exit(1)
    else:
        global pager
        pager = opts['-p']
    if '-t'  not in opts:
       usage(); sys.exit(1)
    else:
        global text
        if  long == 0 :
            text=opts['-t'][0:160] #only the 160 first characters
        else:
            u=(int(nsms))*160
            text=opts['-t'][0:int(u)] #text limited to nsms 


def create_csv(filename):
    """
    create the temporary csv file with the following format
    #COMMAND
    serviceId:255935401
    spaceId:833
    broadcastName:Nagios
    scenarioId:6755
    startDate:2011-11-21 00:00:00
    stopDate:2011-11-21 23:59:59
    callPlanningId:2002
    description:SMS Nagios
    maxSimultaneousContact:2
    customizableId:9956
    multimediaType:TXT
    text:"text du sms 160 caracteres"
    #CONTACTS
    NAME;PHONENUMBER1
    contact;0612345678
    #END
    """
    global dtime
    global tmp_dir
    global tmp_file
    
    debug("->create_csv : creating csv")
    
    try :
        fn=tmp_dir + '/' + filename + '_' + str(dtime)
        tmp_f=open(fn ,  'w')
    except IOError,  err:
        print str(err)
        sys.exit(0)

    tmp_file=tmp_f.name
    debug ("->create_csv : "+tmp_file+' created')
    tmp_f.write('#COMMAND\n'+
        'serviceId:'+serviceid+'\n'+
        'spaceId:'+spaceid+'\n'+
        'broadcastName:Nagios\n'+
        'scenarioId:'+ scenarioid +'\n'+
        'startDate:'+ stime + ' 00:00:00\n'+
        'stopDate:'+stime + ' 23:59:59\n'+
        'callPlanningId:'+callplanningid+'\n'+
        'description:SMS Nagios\n'+
        'maxSimultaneousContact:1\n'+
        'customizableId:'+customizableid+'\n'+
        'multimediaType:TXT\n'+
        'smsLong:' + str(long) + '\n' +
        'text:"'+text+'"\n'+
        '#CONTACTS\n'+
        'NAME;PHONENUMBER1\n'+
        'contact;'+pager+'\n'+
        '#END\n'
    )
    tmp_f.close()
    
    
    
def main():
    """
    main function : call create_csv to create de temporary csv file to send it by ftp 
    establish the ftp connection and upload the csv temporary file
    """
    global tmp_file #filename with absolute path
    
    debug ("->main")
    
    create_csv('ALERT_NAGIOS') #create the temporary before upload it on ftp server
    tmp_fbn=os.path.basename(tmp_file) #basename
    tmp_fbnup= tmp_fbn + '.csv.uploading'#add extension
    
    debug ("->main : ftp login")
    try: #ftp connection
        ftp = FTP('ftp.dmc.sfr-sh.fr') # host,port,login,mdp
        ftp.set_debuglevel(0)
        ftp.login(serviceid,mdp)
        ftp.set_pasv(0) #disable the passive mode
    except ftplib.error_perm,  err:
        print '\nERREUR : ' + str(err) +'\n'
        sys.exit(1)
    

    ftp.cwd('in') #file must be uploaded in the directory 'in'
    debug("->main : send file "+tmp_file)
    ftp.storbinary('STOR ' + tmp_fbnup , open(tmp_file, 'r')) # send temporary file on ftp server; file with extension
    debug ("->main : rename file uploaded " + tmp_fbnup +" in " +  tmp_fbn + '.csv')
    ftp.rename(tmp_fbnup,  tmp_fbn + '.csv' ) #rename the file to be interpreted on server; remove the extension
    ftp.quit() #quit the ftp session
    

def clean():
    """
    delete the temporary file
    """
    #TODO
    debug('->clean')
    debug('->delete '+ tmp_file)
    try :
        os.remove(tmp_file)
    except os.error,  err:
        print str(err)
        sys.exit(1)
    
    
    
######################################
#
#                   MAIN
#
######################################
if __name__ == "__main__":
    check_args()
    main()
    clean()
######################################

