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


def usage():
    print """
    --help      Display this helpful messages
    --execute   Execute the fix.
    --commit    Commit changes.
    """
    return


def main(argv):

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

    enable_fix = False
    commit_changes = 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 ("-c", "--commit"):
            commit_changes = True

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

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

    ctx = AdministrativeContext()
    db = ctx.db_session()

    counter = 0
    query = db.query(Contact).filter(Contact.uid == None).limit(1024)
    result = query.all()
    while result:
        for contact in result:
            values = {
                'carddav_uid': '{0}@{1}'.format(
                    contact.object_id, ctx.cluster_id[1:-1]
                ),
            }
            contact = ctx.r_c('contact::set', object=contact, values=values, )
            print('Setting UID on OGo#{0}'.format(contact.object_id, ))
            counter += 1
        print('{0} contact entities modified'.format(counter, ))
        if commit_changes:
            ctx.commit()
            query = db.query(Contact).filter(Contact.uid == None).limit(1024)
        else:
            result = None
    print('Tool complete, closing context')
    ctx.close()
    sys.exit(0)

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