#!/s/std/bin/perl

#
# make sure SESSION_MANAGER field is set, then fire off gnome-session-save
# with inherited args
#

use Sys::Hostname;

my $icedir = "/tmp/.ICE-unix";
my $dir;
my $user;
my $uid;
my $i;
my @statinfo;
my @getpwinfo;
my @dirs;
my @searchdirs;
my %userhash;
my @execarray;
my $gsave = "/usr/local/bin/gnome-session-save";

opendir(ICEDIR, $icedir) || die "Can't open socket directory $icedir\n";
@dirs = readdir(ICEDIR);
closedir(ICEDIR);

foreach $i (@dirs) {
  # only consider sockets present in this directory
  $dir = $icedir . "/" . $i;
  if ( -S $dir ) {
    push(@searchdirs, $dir);
  }
}

if ($#searchdirs == 0) {
  $dir = pop(@searchdirs);
} else {
  # figure out how to deal with multiple ICE sockets
  foreach $i (@searchdirs) {
    @statinfo = stat($i);
    $userhash{$i} = $statinfo[4];
  }
  $user = $ENV{LOGNAME};
  @getpwinfo = getpwnam $user;
  $uid = $getpwinfo[2];
  $dir = "";
  do {
    $i = pop(@searchdirs);
    if ($userhash{$i} == $uid) {
      $dir = $i;
    }
  } until ($#searchdirs == -1 || $dir =~ /\//);
}

$ENV{SESSION_MANAGER} = "local/" . hostname . ":" . $dir;

push(@execarray, $gsave);

foreach $i (@ARGV) {
  push(@execarray, $i);
}

print "SESSION_MANAGER: $ENV{SESSION_MANAGER} \n";
system(@execarray);
