After much reading and trial and error it seems that what is missing when you run a script as root is that the DBUS_SESSION_BUS_ADDRESS environment variable is not set. This must be set AND the uid changed to that of the user before the gconf settings can be set. This is my test script that I used to try it out. Run one or the other of the system calls at the end to switch the window button order. Try the script as the user or as root (sudo) to see that it works.
#!/usr/bin/perl
use strict;
use warnings;
use POSIX;
# get the user's name (as opposed to root)
my $user_name = getlogin();
# get the uid of the user by name
my $user_uid = getpwnam($user_name);
print $user_name . ": " . $user_uid . "\n";
my %dbus;
# get the DBUS machine ID
$dbus{'machine_id'} = qx{cat /var/lib/dbus/machine-id};
chomp( $dbus{'machine_id'} );
# read the user's DBUS session file to get variable DBUS_SESSION_BUS_ADDRESS
$dbus{'file'} = "/home/" . $user_name . "/.dbus/session-bus/" . $dbus{'machine_id'} . "-0";
print "checking DBUS file: " . $dbus{'file'} . "\n";
if (-e $dbus{'file'}) {
open(FILE, '<', $dbus{'file'});
while(<FILE>) {
if ($_ =~ /^DBUS_SESSION_BUS_ADDRESS=(.*)$/) {
$dbus{'address'} = $1;
print "Found DBUS address: " . $dbus{'address'} . "\n";
}
}
close(FILE);
} else {
print "cannot find DBUS file";
}
# set the uid to the user's uid not root's
POSIX::setuid($user_uid);
# set the DBUS_SESSION_BUS_ADDRESS environment variable
$ENV{'DBUS_SESSION_BUS_ADDRESS'} = $dbus{'address'};
my $command1 = 'gconftool-2 --set "/apps/metacity/general/button_layout" --type string "menu:maximize,minimize,close"';
my $command2 = 'gconftool-2 --set "/apps/metacity/general/button_layout" --type string "menu:minimize,maximize,close"';
system($command1);
## or
#system($command2);
Note: Got some good info here.