#!/usr/bin/python

from email.mime.text import MIMEText

import os
import sys
import string
import smtplib

# Config section
MAILSERVER = 'localhost'
MAILFROM = 'somebody'
MAILTO = 'gerard'


def getpreviouslist(listfile):

    # check for list file and/or create
    try:
        # listfile into list (strip \n)
        fh = open(listfile, 'r')
        returnlist = [x.replace('\n', '') for x in fh]
        fh.close()
        return returnlist

    except IOError:
        try:
            d = open(listfile, 'w')
        except IOError:
            print 'Sorry, I don not have permission to write in parent directory'
            sys.exit()

        for e in os.listdir(dirlist):
            d.write(e)
            d.write('\n')
        d.close()

        print 'No previous listfile, created new one, will do diff on next run'

        # Only wrote new listfile, so byebye
        sys.exit()

def savecurrentlist():
    fh = open(listfile, 'w')
    for x in os.listdir(dirlist):
        fh.write(x)
        fh.write('\n')
    fh.close()


def sendmail(MAILSERVER, MAILFROM, MAILTO, mailbody):
    # Create a text/plain message
    msg = MIMEText('\n'.join(mailbody))

    msg['Subject'] = 'Changes in %s' % dirlist
    msg['From'] = MAILFROM
    msg['To'] = MAILTO

    s = smtplib.SMTP(MAILSERVER)
    s.sendmail(MAILFROM, MAILTO, msg.as_string())
    s.close()


if __name__ == '__main__':

    # 1st argument: absolute path
    try:
        dirlist = sys.argv[1]
    except:
        print 'Sorry, I need a path'
        print '\nUsage: chkdir.py /absolute/path/to/your/location [verbose]\n'
        sys.exit()

    # Check path validity
    try:
        os.stat(os.path.join(dirlist))
    except:
        print 'Sorry, path does not exist\n'
        sys.exit()

    # 2nd argument: Do verbose
    try:
        if sys.argv[2] == 'verbose':
            GPDEBUG = 1
        else:
            # Incase of wrong 2nd arg
            GPDEBUG = 0
    except:
        # Incase of no 2nd arg
        GPDEBUG = 0

    # set listfile for dir 
    listfile = os.path.abspath(dirlist)+'.dirlist'

    # Get oldlist
    oldlist = getpreviouslist(listfile)

    # get current list
    newlist = [x for x in os.listdir(dirlist)]

    if GPDEBUG:
        print 'New list\n', newlist, '\n'
        print 'Old list\n', oldlist, '\n'

    # Check if compare has hits
    if set(oldlist).symmetric_difference(set(newlist)):
        # Initiate mail contents (= list)
        mailbody = []
    
        # Compare diffs new > old
        if set(newlist).difference(oldlist):

            if GPDEBUG:
                print 'Added:'
                print set(newlist).difference(oldlist), '\n'

            mailbody.append('# Added:')
            for x in set(newlist).difference(oldlist):
                mailbody.append(x)

        # Compare diffs old > new
        if set(oldlist).difference(newlist):

            if GPDEBUG:
                print 'Removed:'
                print set(oldlist).difference(newlist), '\n'

            mailbody.append('\n# Removed:')
            for x in set(oldlist).difference(newlist):
                mailbody.append(x)

        sendmail(MAILSERVER, MAILFROM, MAILTO, mailbody)

        savecurrentlist()
                                     
    else:
        if GPDEBUG:
            print 'nodiff'


