#!/srv/projects/coils-code.git/bin/python
#
# Copyright (c) 2012, 2015
#  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.
#
from coils.core import AdministrativeContext, BLOBManager, initialize_COILS
import getopt
import sys
import os


def usage():
    print """
    --help      Display this helpful messages
    --scan      Scan for remnants that could be removed.
    --execute   Remove workflow process remnants.
    """
    return


def main(argv):

    # Process command line arguements
    if not argv:
        usage()
        sys.exit(2)
    try:
        opts, args = getopt.getopt(
            argv,
            "hes",
            ["help", "execute", "scan", ]
        )
    except getopt.GetoptError, e:
        print(e)
        usage()
        sys.exit(2)

    enable_scan = False
    enable_fix = False
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif opt in ("-e", "--execute"):
            enable_fix = True
        elif opt in ("-s", "--scan"):
            enable_scan = True

    # Initialize COILs
    initialize_COILS(
        {
            'log_file': '{0}/coils.log'.format(os.getenv('HOME'), )
        }
    )
    ctx = AdministrativeContext()

    if not enable_scan:
        print('Scan for remnants not requested, see the --scan option.')
        sys.exit(0)

    guids = []
    for filename in BLOBManager.List('shelves'):
        if filename == 'coils.workflow.logger.shelve':
            pass
        else:
            guids.append(filename.split('.')[0])
    print('Found {0} shelves.'.format(len(guids), ))

    bad_guids = []
    for guid in guids:
        process = ctx.run_command('process::get', guid=guid, )
        if not process:
            bad_guids.append(guid)
    print('Found {0} derelict shelves.'.format(len(bad_guids), ))

    if not len(bad_guids):
        print('No derelict shelves exist to be removed, tool complete.')
        sys.exit(0)

    if not enable_fix:
        print(
            'Removal of derelict shelves not requested, '
            'see the --execute option.'
        )
        sys.exit(0)

    for guid in bad_guids:
        print('Deleteing shelve {0}'.format(guid, ))
        BLOBManager.Delete('shelves/{0}.shelve'.format(guid, ))

    print('Tool complete.')

    sys.exit(0)

if __name__ == '__main__':

    main(sys.argv[1:])
