#!/usr/bin/env python
#
# Controls Release Automated Mechanism
# C.R.A.M.
#
from __future__ import print_function

import os
import sys
import toolconfig
import cacheConfig
from six import iteritems

actions = {}
actions['ls'] = ('ls', 'listCurrentReleases', 0,
                 'List the releases currently being used by IOC/HLA/PyDM/other. '
                 'Also for listing available release, unused releases etc.')
actions['push'] = ('push', 'pushRelease', 1,
                   'Pushes/freshens/submits a release for deployment. '
                   'Use push --freshen for updating the contents of an already published release.')
actions['upgrade'] = ('upgrade', 'upgradeRelease', 2,
                      'Upgrades/deploys a IOC/HLA/PyDM/other to use the specified release.')
actions['revert'] = ('revert', 'revertRelease', 3,
                     'Reverts a IOC/HLA/PyDM/other release to the previous release.')
actions['history'] = ('history', 'showHistory', 4,
                      'Displays the upgrade history for a software package.')
actions['delete'] = ('delete', 'deleteRelease', 5,
                     'Delete a previously submitted release from the release repository if it is unused.')
actions['run'] = ('run', 'runReleaseScript', 6,
                  'Run a script in the current release of one or more IOCs/HLA app/PyDM displays in one or more sites/facilities.')
actions['describe'] = ('describe', 'describeRelease', 7,
                       'Generate the configuration needed for rel in the current folder.')
actions['lint'] = ('lint', 'lintRelease', 8, 'Run some basic validations for IOCs to help with cram integration.')
actions['validate'] = ('validate', 'validateLinks', 9,
                       'Do some basic checks to make sure the softlinks for IOCs/HLA applications/PyDM displays are set up correctly.')
actions['configure'] = ('configure', 'cacheConfig', 10, 'Makes a facilities.cfg file specific for the user')
actions['init'] = ('init', 'iocIsBorn', 11, 'Initializes the deployment infrastructure for IOCs/HLA applications/PyDM displays.')

def getActionsListHelp():
    return "\n      ".join(
        map(lambda x: x[0] + " " * (12 - len(x[0])) + x[3], sorted(actions.values(), key=lambda action: action[2])))


def printUsage():
    print("Usage: cram <action> <args>.")
    print("  cram is the main script for the multi site/facility release management system")
    print("  To do something with cram, please specify the action that you'd like to perform.")
    print("  For a list of actions, just type cram.")
    print("  To get help for a particular action, use cram <action> --help.")
    print("  For example, to get help on cram ls, do cram ls --help or cram ls -h")
    print("  Actions currently supported are --")
    print("      " + getActionsListHelp())
    print("  If you encounter any issues, then please contact Murali Shankar/Jingchen Zhou.")
    print("  For high-level documentation, please see " + toolconfig.getDocURL())


if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] == '--help' or sys.argv[1] == '-h':
        printUsage()
        sys.exit(1)

    actionCommand = sys.argv[1]
    actionMatchingPrefix = None
    commandsMatchingPrefix = []
    for action, desc in iteritems(actions):
        if action.startswith(actionCommand):
            commandsMatchingPrefix.append(action)
    if len(commandsMatchingPrefix) == 1:
        actionMatchingPrefix = commandsMatchingPrefix[0]

    if not actionMatchingPrefix:
        print("Command {0} is not recognized".format(actionCommand))
        printUsage()
        sys.exit(1)

    try:
        cacheConfig.createUserFacilityConfig()
    except IOError:
        print("Could not configure a user facility configuration")
        cacheConfig.clean()

    actionDetails = actions[actionMatchingPrefix]
    actionImplementation = actionDetails[1]
    actionExecuteMethod = getattr(__import__(actionImplementation), 'execute')
    actionExecuteMethod(sys.argv[2:])
