#!/usr/bin/python2.6
#
# Copyright (c) 2012
#  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 sqlalchemy import and_
from coils.core import *

def usage():
    print """ WARNING: This fix tool is not entirely transactionally safe.
  Nor is it "safe". Do *NOT* execute this tool unless you know what you
  are doing and have a really sound reason.

  This tool looks for "fake" projects with no type, whose root folder
  contains no content, which contain no tasks, and contains less than
  two assignments (Contacts or Enterprises).  It then deletes these
  projects.  This can greatly diminish the size of the ROOT/documents
  folder as each project is at least a directory (named after the object
  id of the project).  And empty projects are kind of pointless.
  OpenGroupware Legacy, at least certain versions, create a new "fake"
  project for every Enterprise created - ensuring every Enterprise has a
  container for related documents and tasks.  The downside is that results
  in *lots* of unused and pointless projects.  Whether you like this
  behavior or not is a site specific decision.  But if you turn that
  feature off [there is a default for that] you still have all the "fake"
  projects previously created.  In that case maybe you want to use this
  fix tool to eliminated them.  BACKUP FIRST!
  
    --help      Display this helpful messages
    --execute   Execute the fix.
    """
    return

def main( argv ):

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


    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

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

    if not enable_fix:
        print( 'Execution of fix not requested, see the --execute option.' )
        sys.exit( 0 )
            
    db = ctx.db_session()
    # TODO: This query could be smarter, and specifically look for emptry projects
    #       or at least projects that have no tasks
    projects = db.query( Project ).filter( and_( Project.is_fake==1, Project.kind==None ) )
    projects = projects.enable_eagerloads( False )
    # TODO: What about this limit?
    projects = projects.limit( 1000 )

    for project in projects.all( ):
        if ( not project.tasks and 
             not project.folder.folders and
             len(project.folder.files) == 1 and
             len(project.assignments) < 2 ):
            print( 'objectId#{0} candidate for deletion'.format( project.object_id ) )
            if project.assignments:
                enterprise = ctx.run_command( 'enterprise::get', id = project.assignments[ 0 ].child_id )
            print( ' >>> deleting OGo#{0}'.format( project.object_id ) )
            ctx.run_command( 'project::delete', object=project )
        else:
            print( 'objectId#{0} retained.'.format( project.object_id ) )
    ctx.commit()

if __name__ == '__main__':

    main( sys.argv[1:] )
