import sys, os, tempfile
import smtplib
from email.mime.text import MIMEText

def sendwarning(wrn, from_, to_):
    ''' Send warning by email if lock file found'''
    print wrn
    msg = MIMEText(wrn)
    msg['Subject'] = wrn
    msg['From'] = from_
    msg['To'] = to_
    s = smtplib.SMTP('localhost')
    s.sendmail(from_, [to_], msg.as_string())
    s.quit()

def lockproc(lockFile='proc_hab.lock',
             wrn='WARNING!! HAB PROCESSING STOPPED!',
             from_='antonk@johansen.nersc.no',
             to_='anton.korosov@nersc.no'):
    '''Lock processing or give warning'''
    tempDir = tempfile.gettempdir()
    lockFileName = os.path.join(tempDir, lockFile)
    print lockFileName
    if os.path.isfile(lockFileName):
        sendwarning(wrn, from_, to_)
        sys.exit()
    
    # lock other processing
    file(lockFileName, 'w').close()
    return lockFileName
    
