#!/usr/bin/perl -w

use Cyrus::SIEVE::managesieve;

if ($#ARGV < 0) {
	print "Usage: $0 username\n";
	print "  Migrates a single user's .sieve file to the sieve server.\n";
	exit(-1);
}

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


# Build .sieve filename
my ($uid, $gid, $homedir) = (getpwnam($username))[2,3,7];
if (! defined($homedir)) {
	print "Error: Username '$username' not found\n";
	exit;
}
my $sievefile = $homedir . "/.sieve";


# Does this user have a .sieve file in their homedir?
if (! -e "$sievefile") {
	print "$username: no .sieve file\n";
	exit;
}


# Open the .sieve file and read it in
open(IN, "$sievefile") or die ("Could not open '$sievefile' for read - $!");
undef $/;  # enable slurp mode
$sievescript = <IN>;
$/ = "\n";  # return to normal read mode
close(IN);


# 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 sieve server");
}


# Upload it
$rv = sieve_put($sivobj, $scriptname, $sievescript);
if ($rv != 0) { 
	my $errstr = sieve_get_error($sivobj);
	$errstr = "unknown error" if (! defined($errstr));
	print "Upload failed: $errstr\n";
	exit;
}


# Activate it
$rv = sieve_activate($sivobj, $scriptname);
if ($rv != 0) { 
	my $errstr = sieve_get_error($sivobj);
	$errstr = "unknown error" if (! defined($errstr));
	print "Activate failed: $errstr\n";
	exit;
}


sieve_logout($sivobj);


# Move .sieve to .sieve.bak
if (! rename($sievefile, $sievefile . ".txt")) {
	print "Error: unable to rename sievefile\n";
	exit;
}


# Get the text for the replacement .sieve file
my $sievemsgfile = "/private/admin/acct/email/msg.sieveshell_changes";
open(IN, "$sievemsgfile") or die ("Could not open '$sievemsgfile' for read - $!");
undef $/;  # enable slurp mode
my $sievemsg = <IN>;
$/ = "\n";  # return to normal read mode
close(IN);


# Write out the message into .sieve
open(OUT, "> $sievefile") or die ("Could not open '$sievefile' for write - $!");
print OUT $sievemsg;
close(OUT);
chown($uid, $gid, $sievefile);
chmod(0644, $sievefile);



print "Successfully migrated .sieve file for '$username'\n";



# The authentication callback function
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 "";
	}
}

