import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
from os import listdir
from os.path import isdir, join, exists


def get_latest_name(m_path, b_path):
    pt= m_path.replace(b_path,'')
    data =pt.split('/')
    if len(data[0]) > 1:
        return data[0]+'-LATEST.war'
    else:
        return data[1]+'-LATEST.war'

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        if event.event_type == 'created':
            if len(event.src_path) >4:
                if event.src_path[-4:] == '.war' and 'LATEST.war' not in event.src_path:
                    self.update_symbolic_link(event.src_path)

    def update_symbolic_link(self, input_path):
        data = input_path.split('/')
        symbolic_link= "/".join(data[0:5])+"/"+ get_latest_name(input_path,'/var/www/ci_upload/')
        print symbolic_link
        print input_path
        print get_latest_name(input_path,'/var/www/ci_upload/')
        if exists(symbolic_link):
            os.system("rm %s" %symbolic_link)
        print "updating symbolic link"
        os.system("ln -s "+input_path+ " "+ symbolic_link)
        print "garbage old version"
        self.try_to_delete_previous('/var/www/ci_upload/')

    def try_to_delete_previous(self, base_path):
        project_dir = [f for f in listdir(base_path) if isdir(join(base_path, f))]

        for item in project_dir:
            newPath=join(base_path, item)
            folder_dir = [f for f in listdir(newPath) if isdir(join(newPath, f))]
            if len(folder_dir)>10:
                folder_dir.sort()
                for k in  folder_dir[0:-10]:
                    print "Deleting "+join(newPath,k)
                    os.system("rm -rf "+join(newPath,k))


if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='/var/www/ci_upload/', recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()