#!/usr/bin/env python3

import os
import shutil
import sys

def files(path):
    for file in os.listdir(path):
        if os.path.isdir(os.path.join(path, file)):
            yield os.path.join(path, file)

current_pr_value = int(sys.argv[1][3:])
current_build_number = int(sys.argv[2])

base = "/home/eagle0/bin/deploy/"

for file in os.listdir(base):
    os.chdir(base)
    if (os.path.isdir(file)):
        if (file == 'PR-' + str(current_pr_value)):
            # remove old builds
            os.chdir(base + file)

            for innerFile in os.listdir(base + file):
                if innerFile.isnumeric():
                    value = int(innerFile)
                    if (value < current_build_number - 1):
                        print('Removing build ' + innerFile)
                        shutil.rmtree(innerFile)

        elif (file.startswith('PR-')):
            # remove old PRs
            prNumber = int(file[3:])

            if (prNumber < current_pr_value - 3):
                print('Removing old pr ' + str(prNumber))
                shutil.rmtree(file)
