#!/usr/bin/env python
'''Deletes an unused release'''

import os
import sys
import argparse
import subprocess
import globals
import toolconfig
import multi_facility_process_helper_client
import json
import listCurrentReleases
from globals import UserParamsException

def deleteRelease(name, type, releases):
    '''Delete the release specified by release if it is not currently being used'''
    unusedReleases = listCurrentReleases.determineUnusedReleases(name, type)
    for release in releases:
        print "Deleting release", release, "from all facilities"
        if release not in unusedReleases:
            msg = "Release " + release + "is either being used or does not exist"
            raise UserParamsException(msg)
        for facility in toolconfig.getListOfFacilities():
            arg = os.path.join(toolconfig.determineReleaseFolder(facility, name, type), name, release)
            commandsAndArgs = []
            commandsAndArgs.append(('removeFolder', arg))
            results = multi_facility_process_helper_client.executeCommandsOnFacility(facility, commandsAndArgs)
            removeResult = results[0]
            if globals.verbose:
                print "After executing removeFolder, we get ", removeResult



def execute(args):
    parser = argparse.ArgumentParser(prog="cram delete")
    parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose logging')
    parser.add_argument('-n', '--name', help='Specify the application name; we automatically pick this up from the package info if we are running this command in the folder containing the release')
    parser.add_argument('-t', '--type', help='Specifies the type of application from the deployment perspective. Possible values are ' + ", ".join(toolconfig.appTypes.keys()))
    parser.add_argument("releases", help="Please specify one or more releases that were previously submitted and are currently unused.", nargs="+")
    
    args = parser.parse_args(args)
    globals.verbose = args.verbose
    releases = args.releases
    packageInfo = toolconfig.determinePackageInfoFromArgs(args)
    name = packageInfo['name']
    type = packageInfo['type']
    try:
        deleteRelease(name, type, releases)
    except UserParamsException as upe:
        if not globals.verbose and not globals.isunittests:
            print upe
            sys.exit(-1)
        else:
            raise


if __name__ == "__main__":
    execute(sys.argv[1:])

