#!/bin/bash
########################################################################
# Add X11 forwarding to ssh without disturbing other stuff
########################################################################
TMP=`mktemp /tmp/after.rpms.sh.XXXXXX`
trap "rm $TMP* 2>/dev/null" EXIT

if [ -n "$1" ]; then
  file="$1"
else
  file="/etc/ssh/ssh_config"
fi

perl -wan -e \
'
# Found a "Host *" line?
if (/^\s*Host\s+\*/) {
  $host_star = 1;
  $host_star_seen = 1;
  $host_non_star = 0;
}

# Found a "Host blah.domain" line?
if (/^\s*Host\s+[^*]/) {
  $host_star = 0;
  $host_non_star = 1;
}

# Found any extras? Swallow them
$replaced and $host_star and /\s*ForwardX11/i and next;

# Found a good ForwardX11 line to change?
if ($host_star and /^\s*ForwardX11/i and ! $replaced) {
  s/ForwardX11\s+(?:No|no|NO)/ForwardX11 yes/;
  $replaced = 1;
}

# Print the line
print;

# Cleanup
END {
  if (! $replaced) {
    if ($host_star) {
      print "ForwardX11 yes\n";
    } elsif (not $host_star_seen) {
      print "Host *\n";
      print "ForwardX11 yes\n";
    }
  }
}' \
"$file" > "$TMP" && install --backup=numbered -m 644 "$TMP" "$file"

exit $?