#!/usr/bin/env python

import os, sys, glob, commands

from CleanupSettings import *


usage = """removeProjectFrameFiles.py PROJNUM EXTENSION

    REQUIRES:

    PROJNUM    - the project number you want to remove files  from
    EXTENSION   - can be either 'tpr' or 'trr'  (or 'edr', if you know what you're doing!)

    This script will remove all the frame*.tpr (or *.trr) files from the project's
    RUN*/CLONE* directory, except the first frame and the last frame (needed to 
    rebuild each successive WU.
"""


def run(cmd):
    print '>>', cmd
    output = commands.getoutput(cmd)
    print output.strip()

def removeProjectFrameFiles(projnum=None, extension='tpr'):
    """This script will remove all the frame*.tpr (or *.trr or *.edr) files from the project's
    RUN*/CLONE* directory, except the first frame and the last frame (needed to 
    rebuild each successive WU.
    """

    projectDir = os.path.join(projectDataDir, 'PROJ%d'%projnum)
    print 'projectDir', projectDir

    count = 0
    clonedirs = glob.glob( os.path.join(projectDir,'RUN*/CLONE*') )
    for clonedir in clonedirs:
        extfiles = glob.glob( os.path.join(clonedir,'frame*.%s'%extension) )
        if len(extfiles) >= 3:
            extdict = {}
            for extfile in extfiles:
              try:
                frame = int( extfile.split('frame')[1].replace('.%s'%extension,'') )
                extdict[frame] = extfile
              except:
                print 'Unable to parse file %s... Skipping.'%extfile
            keys = extdict.keys()
            keys.sort()
            
            print clonedir 
            print '    Keeping frames', keys.pop(0), # keep the first tpr (trr, edr, etc)
            print '    Keeping frames', keys.pop(),  # keep the last tpr (trr, edr, etc)
            print '    removing frames', keys
            for k in keys:
                count += 1
                cmd = 'rm %s'%extdict[k]       
                run(cmd) 
                print 'Files removed:', count
