#!/usr/bin/env python2.3

"""Script to add/change/delete repository entries in the database.
"""

# Copyright (c) 2004 Infrae. All rights reserved.
# See also LICENSE.txt

import sys

import admconf

###

stderr = sys.stderr

CMDS = ('add', 'show', 'delete')

###

DB = admconf.DB

CON = DB.connect(admconf.dbopts)

###

def usage():
    print >>stderr, 'usage repoadm.py cmd [cmd options]'
    print >>stderr, ' cmds are: %s' % str(CMDS)
    print >>stderr, 'Options:'
    print >>stderr, ' add:'
    print >>stderr, '     repository name'
    print >>stderr, '     master user'
    print >>stderr, '     master password'
    print >>stderr, '     host[:port]'
    print >>stderr, '     path to repository'
    print >>stderr, '     upload path for form based uploads'
    print >>stderr, '     top directory on filesystem'
    print >>stderr, ' delete:'
    print >>stderr, '     repository name'
    print >>stderr, ' show:'
    print >>stderr, '     no arguments'
    return
#

def do_add ( name, muser, mpw, host, path, upath, topdir ):
    print 'adding repository %s' % name
    # sanitize path and topdir
    if path[-1] != '/':
        path += '/'
    if topdir[-1] != '/':
        topdir += '/'
    try:
        DB.add_repository(name, host, path, upath, muser, mpw, topdir)
    except DB.IntegrityError, ex:
        print >>stderr, "Couldn't add repository %s" % name
        print >>stderr, str(ex)
        pass
    return

def do_delete ( name ):
    print 'deleting repository %s' % name
    try:
        DB.delete_repository(name)
    except DB.IntegrityError, ex:
        print >>stderr, "Couldn't delete repository %s" % name
        print >>stderr, str(ex)
        pass
    return

def do_show ():
    print "repository listing:"
    repos = DB.get_all_repos()
    for r in repos:
        print 'Repository: %s' % r['name']
        print '            Id: %s' % r['id']
        print '          Host: %s' % r['host']
        print '          Path: %s' % r['path']
        print '   Upload path: %s' % r['upload_path']
        print ' Top directory: %s' % r['fs_top_dir']
    return

def parse_options( optlist ):
    if not optlist:
        print >>stderr, 'No arguments supplied!'
        usage()
        sys.exit(1)
    cmd = optlist.pop(0).strip().lower()
    if cmd not in CMDS:
        print >>stderr, 'Unknown command: %s' % cmd
        sys.exit(1)
    args = optlist[:]
    try:
        fnc = globals()['do_'+cmd]
    except KeyError, ex:
        print >>stderr, 'No function for command %s found!' % cmd
        sys.exit(2)
    try:
        fnc(*args)
    except TypeError, ex:
        print >>stderr, 'Error: %s' % str(ex)
        usage()
        sys.exit(2)
    return
#
###

if __name__ == '__main__':
    parse_options(sys.argv[1:])
    CON.close()

