#!/usr/bin/perl -w

use Cyrus::SIEVE::managesieve;

if ($#ARGV < 0) {
	print "Usage: $0 username\n";
	exit(-1);
}

require "/private/admin/acct/email/prefs.pl";
my $username = $ARGV[0];
my $realm = "";
my $scriptname = "";
my $sievescript = "";
my $rv = 0;



# Connect to sieve
my $sivobj = sieve_get_handle($prefs{'cyrushost'}, "auth_cb", "auth_cb",
			"auth_cb", "auth_cb");

if (!defined $sivobj) {
	die "unable to connect to server";
}


# Get name of active sieve script
# The callback will set the global variable $scriptname if an active script is found
$rv = sieve_list($sivobj, "list_cb");
if ($rv != 0) { 
	my $errstr = sieve_get_error($sivobj);
	$errstr = "unknown error" if (! defined($errstr));
	print "list failed: $errstr\n";
	exit;
}

print "Scriptname: $scriptname\n";

if ($scriptname ne "") {
	# Get the active script and print it
	$rv = sieve_get($sivobj, $scriptname, $sievescript);
	if ($rv != 0) { 
		my $errstr = sieve_get_error($sivobj);
		$errstr = "unknown error" if (! defined($errstr));
		print "get failed: $errstr\n";
		exit;
	}

	print "Sievescript:\n";
	print "-" x 30 . "\n";
	print $sievescript;
	print "-" x 30 . "\n";
}


sieve_logout($sivobj);


sub auth_cb {
	my ($type, $prompt) = @_;

	if ($type eq "username") {
		return $username;
	}
	elsif ($type eq "authname") {
		return $prefs{'cyrususer'};
	}
	elsif ($type eq "realm") {
		return $realm;
	}
	elsif ($type eq "password") {
		return $prefs{'cyruspass'};
	}
	else {
		return "";
	}
}

sub list_cb {
	my ($name, $isactive) = @_;

	if ($isactive == 1) {
		$scriptname = $name;
	}
}

