#!/usr/bin/perl -l

unless (defined &{$ARGV[0]}) {
    print STDERR <<EOF;
usage: xbannerconfig install | remove | force
  install: add entries to xdm cofiguration to start xbanner
      automatically if they do not already exist
  remove: remove entries from xdm configuration to start xbanner
      automatically
  force: remove then re-add entries to xdm configuration to start
      xbanner automatically
EOF
    exit 1;
}

unless (open FH, "/usr/lib/X11/xdm/xdm-config") {
  print "Can't find xdm config files. Won't try to add xbanner to xdm.";
  exit 0;
}

foreach (<FH>) {
    next unless m{^\s*
		  DisplayManager
		  (?:\._\d+\.|\*)
		  (setup|startup)
		  \s*:\s*(?:\\\n)?\s*
		  (\S+)}x;

    unless (-f $2  and open IN, $2) {
	print "Can't find xdm config files. Won't try to add xbanner to xdm.";
	exit 0;
    }

    $stat{$2} = [stat (_)];

    my $file = $$1{$2} = [];
    push @$file, <IN>;
    chomp @$file;
    close IN;
}

&{$ARGV[0]};

foreach (%setup, %startup) {
    if (! ref) {
	close FH;
	open FH, "> $_.$$" or exit 1;
    }
    else {
	print FH join "\n", @$_;
    }
} 
close FH;

foreach (keys %stat) {
    rename "$_.$$", $_ or next;
    chmod ${$stat{$_}}[2], $_;
    chown @{$stat{$_}}[4,5], $_;
    utime @{$stat{$_}}[8,9], $_;
}

print "WARNING: Modification of xdm files incomplete! Please check."
    if grep {-f "$_.$$" and unlink "$_.$$"} keys %stat;

print 'Xdm files modified ',
    ($ARGV[0] eq 'remove' && 'not '),'to run xbanner.';

exit 0;

sub force {
    remove();
    install();
}

sub remove {
    foreach (values %setup, values %startup) {
	@$_ = grep !(m!^#\s*XBanner -! || 
		     m!^\s*/usr/X11R6/bin/(?:xbanner|freetemp)!), @$_;
    }
}

sub install {
    foreach (values %setup) {
	exit 0
	    if grep m!^\s*/usr/X11R6/bin/xbanner!, @$_;
    }

    print <<EOF;

Xbanner configuration
---------------------

A popular use of xbanner is to make it run when xdm is run, to beautify
the xdm login screen. I can modify some files to make this work, if you
want.
EOF

    {
	local $\ = undef;
	print "Should I modify xdm files to make xbanner be launched on xdm startup? [Y/n] ";
    }
    if (<STDIN> =~ m!^\s*[nN]!) {
	print "All right, I won't do that.";
	exit 0;
    }

    foreach (values %setup) {
	my $i = @$_;
	while ($i--) {
	    next if $_->[$i] =~ m!^\s*(?:exit(?:\s+0)?\s*)?$!;
	    ++$i;
	    splice @$_, $i, ($_->[$i] =~ m!^\s*$!), split "\n", q{
# XBanner - begin
/usr/X11R6/bin/freetemp
/usr/X11R6/bin/xbanner -file /etc/X11/XBanner.ad
# XBanner - end
}, -1;

	    last;
	}
    }

    foreach (values %startup) {
	my $i = @$_;
	while ($i--) {
	    next if $_->[$i] =~ m!^\s*(?:exit(?:\s+0)?\s*)?$!;
	    ++$i;
	    splice @$_, $i, ($_->[$i] =~ m!^\s*$!), split "\n", q{
# XBanner - begin
/usr/X11R6/bin/freetemp
# XBanner - end
}, -1;

	    last;
	}
    }
} 
