#!/usr/bin/python2.3

# Copyright 2003 Iustin Pop
#
# This file is part of cfvers.
#
# cfvers is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# cfvers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cfvers; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import cfvers
try:
    from optparse import OptionParser
except ImportError:
    from optik import OptionParser
import os, os.path
import sys
import types

class CLI(object):
    def __init__(self):
        commands = {
            'init': (self.cmd_init, "Initializes the repository (do it only ONCE!)"),
            'info': (self.cmd_info, "Display informations about the areas present"),
            'create': (self.cmd_create, "Creates a new area"),
            }
        self.curr_cmd = "<command>"
        self.usage="usage: %prog [global options] command [command options and arguments]\nwhere command is one of\n"
        l = commands.keys()
        l.sort()
        for i in l:
            self.usage += "    %-10s %s\n" % (i, commands[i][1])
        self.usage += "\nGlobal options:"
        self.commands = commands
    
    def get_scp(self, earg):
        """Returns a sub-command parser"""
        op = OptionParser(version=cfvers.cmd.CLIScript.get_version(),
                          usage="%%prog [global options] %s [options] " \
                          "%s\nFor global options, see %%prog --help" \
                          % (self.curr_cmd, earg))
        return op

    def main(self, argv):
        op = OptionParser(version=cfvers.cmd.CLIScript.get_version(),
                          usage=self.usage)
        op.disable_interspersed_args()

        op.add_option("-d", dest="repository",
                      help="the repository path",
                      type="string", default=None,
                      metavar="REPOSITORY")

        (options, args) = op.parse_args(argv)
        options.area = None
        if len(args) == 0:
            op.print_help()
            return
        command = args.pop(0)
        if not command in self.commands:
            print "Unknown command %s" % command
            op.print_help()
            return
        self.curr_cmd = command
        func = self.commands[command][0]
        func(options, args)
        return
        
    def cmd_init(self, options, args):
        """Initialize the local repository"""
        op = self.get_scp("")
        op.add_option("--force", dest="force",
                      help="drop existing schema first",
                      action="store_true", default=False,
                      )
        op.add_option("--skip-data", dest="doarea",
                      help="skip data creation",
                      action="store_false", default=True,
                      )
        (cmdoptions, cmdargs) = op.parse_args(args)
        cfvers.AdminCommands.init_repo(options, cmdoptions)
        return

    def cmd_create(self, options, args):
        """Creates a new area"""
        op = self.get_scp("area_name")
        op.add_option("-d", "--description", dest="description",
                      help="area description",
                      type="string", 
                      metavar="TEXT")
        defserver = os.uname()[1]
        op.add_option("-p", "--rootpath", dest="root",
                      help="filesystem root of the area [/]",
                      type="string", default="/",
                      metavar="PATH")
        
        (cmdoptions, cmdargs) = op.parse_args(args)
        if len(cmdargs) != 1:
            print >>sys.stderr, "You must give the area name!!"
            return
        cmd = cfvers.AdminCommands(options)
        cmd.create_area(cmdoptions, cmdargs[0])
        cmd.close()
        return

    def cmd_info(self, options, args):
        """Show informations about the local repository"""
        op = self.get_scp("")
        (cmdoptions, cmdargs) = op.parse_args(args)
        cmdi = cfvers.AdminCommands(options)
        r = cmdi.repo
        print "Local repository has %d area(s)" % r.numAreas()
        for a in r.areas():
            print "-" * 25
            print "Name: %s" % a.name
            print "Created at %s %s" % (a.ctime.localtime().strftime("%Y-%m-%d %T"), a.ctime.tz)
            print "Root path: %s" % a.root
            print "Description: %s" % a.description
            if a.revno is None:
                print "No revisions in this area"
            else:
                print "Revision number: %d" % a.revno
            print "Number of items: %d" % a.numitems
        return
    

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