#!/usr/bin/php
<?php

if (!file_exists('/etc/sasldb2')) die("/etc/sasldb2 not found!\n");

$out = `db_dump -d a /etc/sasldb2`;
if (empty($out)) die("Cannot read /etc/sasldb2! Is db_dump installed?\n");

# TODO: the chmod-values will not be copied!
copy('/etc/sasldb2', '/etc/sasldb2.bak');

preg_match_all('@data: ([^\r\n]*)\\\0([^\r\n]*)\\\0userPassword.+data: (.*)([\r\n]|$)@ismU', $out, $m, PREG_SET_ORDER);
foreach ($m as $ary) {
	$username = $ary[1];
	$host = $ary[2];
	$password = $ary[3];
	echo "Processing $username@$host ...\n";

	`saslpasswd2 -d $username@$host`;
	`echo "$password" | saslpasswd2 -p -c $username`;
}

