#!/usr/bin/env python
##
# Copyright (c) 2005-2007 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# DRI: David Reid, dreid@apple.com
##

import os
import sys
import fnmatch
import plistlib

ServiceConf = "85-calendarServer.plist"

configFile = "/private/etc/caldavd/caldavd.plist"

documentRoot = "/Library/CalendarServer/Documents/"

removePatterns = ['.db.sqlite']


class Options(dict):
    def parseOpts(self, argv):
        for x in xrange(0, len(argv)):
            opt = argv[x]
            if opt.startswith('-'):
                self[opt.strip('-')] = argv[x+1]


def cleanDocRoot():
    root = None
    if os.path.exists(configFile):
        root = plistlib.readPlist(configFile)['DocumentRoot']
        
    if not root and os.path.exists(configFile + '.default'):
        root = plistlib.readPlist(configFile + '.default')['DocumentRoot']

        if not root: 
            root = documentRoot

    if not root:
        print "Could not find document root"
        sys.exit(1)

    removed = []

    for root, dirs, files in os.walk(root):
        dirs.extend(files)
        for file in dirs:
            for pat in removePatterns:
                if fnmatch.fnmatch(file, pat):
                    full = os.path.join(root, file)

                    os.remove(full)

                    removed.append(full)
                  
    return removed


def cmd_restore(options):
    cleanDocRoot()


if __name__ == '__main__':
    options = Options({'cmd': None,
                       'target': None,
                       'path': None,
                       'log': None,
                       'opt': 'all'})

    options.parseOpts(sys.argv[1:])
    
    cmd = globals().get('cmd_%s' % (options['cmd'],), None)

    if not cmd:
        print "Unknown Command: %s" % (options['cmd'],)
        sys.exit(1)

    cmd(options)
