#!/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, release):
    '''Delete the release specified by release if it is not currently being used'''
    unusedReleases = listCurrentReleases.determineUnusedReleases(name, type)
    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("release", help="Please specify a release that was previously submitted.")
    
    args = parser.parse_args(args)
    globals.verbose = args.verbose
    release = args.release
    packageInfo = toolconfig.determinePackageInfoFromArgs(args)
    name = packageInfo['name']
    type = packageInfo['type']
    try:
        deleteRelease(name, type, release)
    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:])

