#!/bin/bash
########################################################################
# Configure kdmrc to allow qiv to show picture.
########################################################################
TMP=`mktemp /tmp/after.rpms.sh.XXXXXX`
trap "rm $TMP* 2>/dev/null" EXIT

if [ -n "$1" ]; then
  file="$1"
else
  file="/etc/X11/xdm/kdmrc"
fi

perl -wan -e \
'
# Found a blank line (interpret as end-of-section)?
if (/^\s*$/) {
  if ($local_core and !$replaced_rootlogin) {
    print "AllowRootLogin=true # Added by BooNE config-kdmrc\n";
  }
  if ($local_greeter and !$replaced_usebackground) {
    print "UseBackground=false # Added by BooNE config-kdmrc\n";
  }
  $local_greeter = 0;
  $local_core = 0;
}

# Found a local Greeter line?
if (/^\s*\Q[X-:*-Greeter]\E/) {
  $local_greeter = 1;
  $local_greeter_seen = 1;
}

# Found a local Core line?
if (/^\s*\Q[X-:*-Core]\E/) {
  $local_core = 1;
  $local_core_seen = 1;
}

# Found a good AllowRootLogin line to change?
if ($local_core and /^\s*AllowRootLogin/i) {
  s/=.*$/=true # Edited by BooNE config-kdmrc/;
  $replaced_rootlogin = 1;
}

# Found a good UseBackground line to change?
if ($local_greeter and /^\s*UseBackground/i) {
  s/=.*$/=false # Edited by BooNE config-kdmrc/;
  $replaced_usebackground = 1;
}

# Print the line
print;

# Cleanup
END {
  if ($local_core and !$replaced_rootlogin) {
    print "AllowRootLogin=true\n\n";
  }
  if ($local_greeter and !$replaced_usebackground) {
    print "UseBackground=false\n\n";
  }
  if (!$local_greeter_seen) {
    print STDERR "Could not find local Greeter section to edit!\n";
  }
  if (!$local_core_seen) {
    print STDERR "Could not find local Core section to edit!\n";
  }
}' \
"$file" > "$TMP" && install --backup=numbered -m 644 "$TMP" "$file"

exit $?
