#!/usr/bin/python
# Copyright (c) 2010 Adam Tauno Williams <awilliam@whitemice.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

# TODO: Add usage information

from coils.core  import *
import getopt, sys, os

def usage():
    print """

    """
    return

def main(argv):

    try:
        ctx, params = initialize_tool('delete-pocess', argv, arguments=('p:', ['pid=']))
    except getopt.GetoptError, e:
        print 'unable to initialize OpenGroupware Coils subsystem'
        print e
        sys.exit(2)

    pid = params.get('--pid', None)
    if (pid is None):
        print 'No process id specified'
        sys.exit(4)

    process = ctx.run_command('process::get', id=pid)
    if (process is None):
        print 'No such process as {0}'.format(pid)
        sys.exit(5)
    if (process.state in ('Q', 'F', 'C', 'I', 'Z')):
        process = None
        print 'Deleting process {0}'.format(pid)
        ctx.run_command('process::delete', id=pid)
        ctx.commit()
    else:
        print 'Cannot delete a process in state {0}, you must first fail this process.'.format(process.state)
    ctx.close()

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