#! /usr/bin/perl -w

package ag_cyrus_conf;
# FIXME: How should that be handled?
use lib qw(/usr/lib/YaST2/servers_non_y2);
use strict;
use CyrusConfParser;
use YaST::SCRAgent;
use ycp;
our @ISA = ("YaST::SCRAgent");

my $_CFINST = undef;

sub check_initialized ()
{
    my $class = shift;
    if (not defined $_CFINST)
    {
        $class->SetError(summary => "Agent not initialized yet",
                         code => "SCR_INIT_ERR");
    }
    return !!$_CFINST;
}

sub OtherCommand () {
    my $class = shift;
    my ($symbol, $config, @rest) = @_;
    
    if ($symbol ne "CyrusConf") {
        return $class->SetError(summary=> "The first command must be the configuration.(Seen '$_')",
                                code => "SCR_INIT_ERR");
    } else {
        $_CFINST = new CyrusConfParser( $config->{"file"}, \&y2error );
        if( not defined $_CFINST ) {
            return $class->SetError(summary => "Can not initialize CyrusConfParser",
                                    code => "SCR_INIT_ERR");
        }
	if( $_CFINST->readCyrusConf() ) {
            return $class->SetError(summary => "Can not read cyrus.conf",
                                    code => "SCR_INIT_ERR");
	}
	# FIXME: Set logging callback here
    }
    
    return 1;
}

sub Read { 
    my $class         = shift;
    my ($path, @args) = @_;

    if( $_CFINST->readCyrusConf() ) {
	# FIXME: How about $class->SetError() ???
	return undef;
    }
    
    return 1;
}

sub Write { 
    my $class         = shift;
    my ($path, @args) = @_;

    return undef if ! $class->check_initialized();
    if( $_CFINST->writeCyrusConf() ) {
	# FIXME: How about $class->SetError() ???
	return undef;
    }

    return 1; 
}

sub Execute {
    my $class         = shift;
    my ($path, @args) = @_;

    return undef if ! $class->check_initialized();

    if( $path eq '.toggleService' ) {
	my $service = $args[0];
	return undef if $_CFINST->toggleService( $service );
    } elsif ( $path eq '.addService' ) {
	my $service = $args[0];
	return undef if $_CFINST->addService( $service );
    } elsif ( $path eq '.serviceExists' ) {
	my $service = $args[0];
	return $_CFINST->serviceExists( $service );
    } elsif ( $path eq '.serviceEnabled' ) {
	my $service = $args[0];
	return $_CFINST->serviceEnabled( $service );
    }

    return undef; 
}
  

package main;
ag_cyrus_conf->Run;
