eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}'
                  && eval 'exec perl -w -S $0 $argv:q'
                  if 0;

########################################################################
########################################################################

use strict;

use Getopt::Long;
use File::Basename;
use File::Path;
use Pod::Usage;

my $gratia_dir;
if (-l $0) {
  $gratia_dir = dirname(readlink($0));
} else {
  $gratia_dir = dirname $0;
}

my %collector_configs = ();

my @collector_wars =
  qw(administration registration services servlets soap);

my @reporting_wars = qw(reporting reports);

my @required_attributes =
  (
   'http_port',
   'rmi_port',
   'db_schema',
   'UserConfig',
   'sslCAFiles',
   'crlFiles',
   'staticReports'
  );

my @required_properties = ();

my %attribute_defaults =
  (
   max_perm_size => "128m",
   max_heap_size => "256m",
   db_port => 3306,
   db_host => "gratia-db01.fnal.gov",
   UserConfig => "UserConfig_osg.xml",
   UserConfigPath => "gratia-reports/MenuConfig/",
   PostInstallCmdPreamble => "",
   PostInstallCmdPrefix => "",
   PostInstallCmdSuffix => "",
   staticReports => 1,
   host_cert => "/etc/grid-security/hostcert.pem",
   host_key => "/etc/grid-security/hostkey.pem",
   sslCAFiles => "/etc/grid-security/certificates/*.0",
   crlFiles => "/etc/grid-security/certificates/*.r0",
   service_auto_start => 1,
   want_collector => 1,
   want_reporting => 1,
   robots => "User-agent: *\nDisallow: /\n",
   "properties.attributes" =>
   {
    "service.initial.servlets" => "ON",
    "service.initial.recordProcesor" => "ON",
    "service.initial.replication" => "ON",
    "service.initial.housekeeping" => "ON",
    "service.rmi.service" => "/gratia",
    "use.report.authentication" => "true",
    "maintain.history.log" => 14,
    "service.mysql.user" => "gratia",
    "service.mysql.password" => "proto",
    "service.reporting.user" => "reader", # new
    "service.reporting.password" => "reader", # new
    "monitor.recordProcessor.threads" => "true",
    "monitor.recordProcessor.wait" => 240,
    "monitor.q.size" => 1,
    "max.q.size" => 100000,
    "monitor.smtp.server" => "smtp.fnal.gov",
    "monitor.smtp.authentication.required" => "false",
    "monitor.smtp.user" => "greenc",
    "monitor.smtp.password" => "",
    "monitor.from.address" => 'grid-accounting@fnal.gov',
    "monitor.to.address.0" => 'pcanal@fnal.gov',
    "monitor.to.address.1" => 'greenc@fnal.gov',
    "monitor.subject" => \&construct_monitor_message_subject,
    "service.rmiservlet.console" => 0,
    "service.security.console" => 0,
    "service.vdt.cert.file" => "/etc/grid-security/http/httpcert.pem",
    "service.vdt.key.file" => "/etc/grid-security/http/httpkey.pem",
    "service.recordProcessor.threads" => 1,
    "service.lifetime.JobUsageRecord" => "1 year", # May wish to dencrease
    "service.lifetime.JobUsageRecord.RawXML" => "1 month",
    "service.lifetime.MetricRecord" => "3 months", # Shouldn't get these at all
    "service.lifetime.MetricRecord.RawXML" => "1 month",
    "service.lifetime.ComputeElementDescription" => "3 months", # Shouldn't get these at all
    "service.lifetime.DupRecord.Duplicate" => "1 month",
    "service.lifetime.DupRecord.ExpirationDate" => "1 month",
    "service.lifetime.DupRecord.CutoffDate" => "1 month",
    "service.lifetime.DupRecord" => "UNLIMITED",
    "service.lifetime.Trace" => "6 months",
    "service.lifetime.Trace.add_JUR_to_summary" => "3 months"
   }
  );

my $tomcat_users_txt = <<'EOF';
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="gratia" password="proto" fullName="gratia prototype user" roles="admin,manager"/>
  <user username="root" password="lisp01" roles="admin,manager"/>
</tomcat-users>
EOF

my $root_index_html = <<'EOF';
<html>

<head>
<meta http-equiv="refresh" content="0;URL=/gratia-reporting/">
</head>

<body>
</body>

</html>
EOF

my $init_script_template = <<'EOF';
#!/bin/bash
#
# tomcat-<instance>     Start and stop an instance of the standalone tomcat service.
#
# chkconfig: 345 99 50
# description: Standalone tomcat invocation for the Gratia service

####################################
# Ensure these variables are set as appropriate
JAVA_HOME=
TOMCAT_HTTP_PORT=
TOMCAT_PATH_STEM=
TOMCAT_SSL_PORT=
TOMCAT_USER=
JSVC=
REDIRECT_REPORTING=
####################################
export JAVA_HOME

prog_base=$(basename ${0})
[[ "$prog_base" == *-all ]] && REDIRECT_REPORTING="false"
prog_base=${prog_base%-all}

# This should be fine as a default
TOMCAT_INSTANCE_NAME=`echo "$prog_base" | sed -e 's/^.*\(tomcat-.*\)$/\1/'`

########################################################################
# No User Servicable Parts
CATALINA_HOME="${TOMCAT_PATH_STEM}/${TOMCAT_INSTANCE_NAME}"; export CATALINA_HOME
CATALINA_PID=/var/run/catalina.pid
CATALINA_TMPDIR=/tmp
[[ -n "${TOMCAT_SSL_PORT}" ]] && TOMCAT_SSL_ARG="-Dssl_port=${TOMCAT_SSL_PORT} "
[[ -n "${KRB5CCNAME}" ]] && KRB5CCNAME=`echo "${KRB5CCNAME}" | sed -e 's/^FILE://'`

. /etc/init.d/functions

PATH="${PATH}:${JAVA_HOME}/bin" # Needed for SSL keytool

function check_hostkeys {
  for i in /etc/grid-security/hostkey-*.pem; do
    [[ /etc/grid-security/hostkey.pem -nt "$i" ]] && \
      cat /etc/grid-security/hostkey.pem > "$i"
  done
}

function start {
  JAVA_OPTS="-server"; export JAVA_OPTS
  CATALINA_OPTS="-Dsun.net.inetaddr.ttl=297 -Dcom.sun.management.jmxremote ${TOMCAT_SSL_ARG}-Dcom.mchange.v2.c3p0.management.ManagementCoordinator=com.mchange.v2.c3p0.management.NullManagementCoordinator"; export CATALINA_OPTS
  find "$CATALINA_HOME"/webapps -path '*/WEB-INF/urlrewrite.xml' | xargs perl -wapi.bak -e 's/enabled\s*=\s*".*?"(.*<!-- Controlled by REDIRECT_REPORTING in service start -->.*)$/enabled="'"$REDIRECT_REPORTING"'"$1/'
  check_hostkeys
  if [[ -n "$JSVC" ]] && [[ -x "$JSVC" ]] && [[ -n "$TOMCAT_USER" ]]; then
    echo -n "Starting tomcat-gratia: "
    # daemon function does not run pam hooks, so /etc/security/limits.conf has no effect.
    ulimit -n 8192
    daemon --pidfile="$CATALINA_PID" "$JSVC" -user $TOMCAT_USER \
      -cp "$CATALINA_HOME"/bin/bootstrap.jar \
      -outfile "$CATALINA_HOME"/logs/catalina.out \
      -errfile "$CATALINA_HOME"/logs/catalina.err \
      -pidfile "$CATALINA_PID" \
      ${CATALINA_OPTS} \
      -Djava.endorsed.dirs="$CATALINA_HOME"/common/endorsed \
      -Dcatalina.home="$CATALINA_HOME" \
      -Djava.io.tmpdir="$CATALINA_TMPDIR" \
      org.apache.catalina.startup.Bootstrap start
    echo
  else
    if [[ -n "${TOMCAT_USER}" ]]; then
      su -c "${CATALINA_HOME}/bin/catalina.sh start" ${TOMCAT_USER}
    else
      $CATALINA_HOME/bin/catalina.sh start
    fi
  fi
}

function stop {
  if [[ -n "$JSVC" ]] && [[ -x "$JSVC" ]] ; then
    echo -n "Stopping tomcat-gratia: "
    killproc -p "$CATALINA_PID" "$JSVC" -TERM
    echo
  else
    if [[ -n "${TOMCAT_USER}" ]]; then
      su -c "${CATALINA_HOME}/bin/shutdown.sh" ${TOMCAT_USER}
    else
      ${CATALINA_HOME}/bin/shutdown.sh
    fi
  fi
}

function is_running {
  local result
  if [[ -n "$JSVC" ]] && [[ -x "$JSVC" ]]; then
    status -p "$CATALINA_PID" "$JSVC" >/dev/null 2>&1
    result=$?
  else
    local process_cnt="$(ps -ef | grep -E -e "file=$TOMCAT_PATH_STEM/$TOMCAT_INSTANCE_NAME" | grep -E -e '  1 ' | grep -E -v grep | wc -l)"
    case $process_cnt in
      0) result=1
         ;;
      1) result=0
         ;;
      *) result=2
         ;;
    esac
  fi
  return $result
}

if [ "$1" = "start" ] ; then
  start
elif [ "$1" = "stop" ] ; then
  stop
elif [ "$1" = "status" ] ; then
  is_running
  s=$?
  if (( $s == 0 )) ; then
    echo -n "tomcat-gratia is running"
    if [[ -n "$CATALINA_PID" ]] && [[ -r "$CATALINA_PID" ]]; then
      echo " (pid $(cat $CATALINA_PID))"
    else
      echo
    fi
  else
    echo "tomcat-gratia is not running"
  fi
elif [ "$1" = "restart" ]; then
  if is_running; then
    stop
    echo "Pause ..."
    sleep 20
    start
  else
    echo "${TOMCAT_INSTANCE_NAME} does not appear to be running: not attempting to restart"
    exit 1
  fi
else
  echo "Usage: ${TOMCAT_INSTANCE_NAME} [start | stop | restart | status]"
  exit 1
fi
EOF

my %options = ();

my $default_java_home = "/scratch/java";
my $default_remote_host = `uname -n`;
chomp $default_remote_host;
my $default_prefix = "/scratch";

my @default_collector_info =
  ( "collector-nbuild.dat",
    "collector-dev.dat" );

Getopt::Long::Configure(qw(no_ignore_case bundling require_order));

GetOptions(\%options, "java-home|j=s",
           "remote-host|r=s",
           "use-ssl|s",
           "prefix|p=s",
           "db-root|d=s",
           "collector-info|c=s@",
           "print-config",
           "obtain-config-item|print-config-item=s@",
           "obtain-properties-item|print-properties-item|print-property=s@",
           "help|h|\?") or pod2usage(-exitval => 2);

pod2usage(-exitval => 1, -verbose => 3) if $options{help};

if ($options{"use-ssl"}) {
  print STDERR "INFO: ignoring obsolete option use-ssl. SSL will be configured if ssl_port is specified in config\n";
}

unless (exists $options{"java-home"} or
        exists $options{"obtain-config-item"} or
        exists $options{"obtain-properties-item"}) {
  if (-d $default_java_home) {
    print STDERR "INFO: using default JAVA_HOME $default_java_home\n";
    $options{"java-home"} = $default_java_home;
  } else {
    print STDERR "ERROR: JAVA_HOME not specified and default \"$default_java_home\" does not exist as a directory\n";
    pod2usage(-exitval => 1);
  }
}

unless (exists $options{prefix}) {
  if (-d $default_prefix and -w $default_prefix) {
    print STDERR "INFO: tomcat install prefix not specified, ",
      "using default \"$default_prefix\"\n";
    $options{prefix} = $default_prefix;
  } else {
    if (wants_config_info()) {
      print STDERR "WARNING: tomcat install prefix not specified ",
        "and default \"$default_prefix\"",
          "\n does not exist as a directory or is not writable.\n";
      print STDERR " Therefore config information will not be taken from the installed release.\n";
    } else {
      print STDERR "ERROR: tomcat install prefix not specified ",
        "and default \"$default_prefix\"",
          "\ndoes not exist as a directory or is not writable\n";
      Pod2usage(-exitval => 1);
    }
  }
}

pod2usage(-exitval => 1) unless scalar @ARGV;

my @instance_list = @ARGV;

unless (exists $options{"collector-info"} and scalar @{$options{"collector-info"}}) {
  $options{"collector-info"} = [ @default_collector_info ];
}


foreach my $config_name (@instance_list) {
  foreach my $dat_file (@{$options{"collector-info"}}) {
    $dat_file = find_dat_file($dat_file);
    if (not open(DAT_SOURCE, $dat_file)) {
      print STDERR "ERROR: Unable to open data file $dat_file\n";
      next;
    }
    my $dat_source = join('', <DAT_SOURCE>);
    close DAT_SOURCE;
    my %tmp_hash = eval $dat_source;
    if ($@) {
      print STDERR "ERROR: Problem reading collector data file $dat_file\n";
      next;
    }
    if (exists $tmp_hash{$config_name}) {
      $collector_configs{$config_name} = $tmp_hash{$config_name};
      print STDERR "INFO: found configuration for instance, \"$config_name\" in $dat_file\n";
      last;
    }
  }

  my $collector_config = $collector_configs{$config_name};

  if (not $collector_config) {
    print STDERR "WARNING: configuration for specified gratia instance $config_name not found!\n";
    exit 1;
  }

  # attributes.properties container if not previously existing.
  $collector_config->{"properties.attributes"} = {}
    unless exists $collector_config->{"properties.attributes"};

  # Standard attribute defaults.
  foreach my $attribute_key (sort keys %attribute_defaults) {
    $collector_config->{$attribute_key} = $attribute_defaults{$attribute_key}
      unless exists $collector_config->{$attribute_key};
  }

  # Properties attribute defaults.
  my $specified_addresses = grep m&monitor\.to\.address&o, keys %{$collector_config->{"properties.attributes"}};
  foreach my $properties_key (sort keys %{$attribute_defaults{"properties.attributes"}}) {
    # Skip all default email addresses if we specified any at all.
    next if $specified_addresses and $properties_key =~ m&monitor\.to\.address&o;
    unless (exists $collector_config->{"properties.attributes"}->{$properties_key}) {
      my $obsolete_key = $properties_key;
      if ($obsolete_key =~ s&\.recordProcessor\.&.listener.& and
          exists $collector_config->{"properties.attributes"}->{$obsolete_key}) {
        print STDERR "INFO: upgrading obsolete specified property ",
          $obsolete_key, " to replacement property ", $properties_key, "\n";
        $collector_config->{"properties.attributes"}->{$properties_key} =
          $collector_config->{"properties.attributes"}->{$obsolete_key};
        delete $collector_config->{"properties.attributes"}->{$obsolete_key};
      } else {
        $collector_config->{"properties.attributes"}->{$properties_key} =
          $attribute_defaults{"properties.attributes"}->{$properties_key};
      }
    }
  }

  # Must correct dependent settings here.
  $collector_config->{staticReports} = 0 unless
    $collector_config->{want_reporting};


  # Required attributes
  my $requirements_error = 0;
  foreach my $required_attribute (@required_attributes) {
    unless (exists $collector_config->{$required_attribute}) {
      print STDERR "Configuration for instance \"$config_name\" does not have ",
        "required attribute \"$required_attribute\"\n";
      $requirements_error = 1;
    }
  }

  foreach my $required_attribute (@required_properties) {
    unless (exists $collector_config->{"properties.attributes"}->{$required_attribute}) {
      print STDERR "Configuration for instance \"$config_name\" does not have ",
        "required properties.attributes entry \"$required_attribute\"\n";
      $requirements_error = 1;
    }
  }

  # Next if failed requirements.
  next if $requirements_error;

  my $instance_name = $collector_config->{instance_name} || $config_name;

  # Maybe print requested config information and exit
  maybe_print_config_info($instance_name, $config_name, $collector_config) and exit(0);

  # Check and (maybe) override remote_host setting
  verify_remote_host_setting($instance_name, $config_name, $collector_config);

  # Configuration operations.
  configure_keyfile_owners($instance_name, $config_name, $collector_config);
  configure_collector_config($instance_name, $config_name, $collector_config);
  configure_init_file($instance_name, $config_name, $collector_config);
  configure_tomcat_config($instance_name, $config_name, $collector_config);
  configure_ROOT($instance_name, $config_name, $collector_config);
  maybe_configure_tmpwatch($instance_name, $config_name, $collector_config);
  configure_tomcat_users($instance_name, $config_name, $collector_config);
  maybe_restrict_services($instance_name, $config_name, $collector_config);
  configure_static_report_generation($instance_name, $config_name, $collector_config);
  configure_name_file($instance_name, $config_name, $collector_config);

  unless (exists $options{"db-root"}) {
    my ($db_short_host) = ($collector_config->{"db_host"} =~ m&^([^\.]+)&);
    my $alternative_pw_file = "$options{prefix}/.mysql-${db_short_host}";
    print STDERR "INFO: no DB root password specified in options: checking for $alternative_pw_file\n";
    if (-r $alternative_pw_file) {
      my @stat = stat($alternative_pw_file);
      if ($stat[4] != 0) {
        print STDERR "WARNING: $alternative_pw_file not owned by root: DB root user may be insecure!\n";
      }
      if ($stat[2] != 0600) {
        print STDERR "WARNING: unsafe permissions on $alternative_pw_file: DB root user may be insecure!\n";
      }
      $options{"db-root"} = `cat "${alternative_pw_file}"`;
      chomp $options{"db-root"};
    } else {
      print STDERR "WARNING: no DB root password specified and no file $alternative_pw_file assuming an empty password.\n";
    }
  }
  configure_post_install($instance_name, $config_name, $collector_config);

  configure_installation_owner($instance_name, $config_name, $collector_config);

}

1;

#--------------------------------------
sub configure_ROOT {
  my ($instance_name, $config_name, $collector_config) = @_;
  open(INDEX_HTML,
       ">$options{prefix}/tomcat-${instance_name}/webapps/ROOT/index.html") or do {
         print STDERR "ERROR: unable to open $options{prefix}/tomcat-${instance_name}/webapps/ROOT/index.html for write.\n";
         exit 1;
       };
  print INDEX_HTML $root_index_html;
  close INDEX_HTML;
  if ($collector_config->{robots}) {
    open (ROBOTS_TXT, ">$options{prefix}/tomcat-${instance_name}/webapps/ROOT/robots.txt") or do {
      print STDERR "ERROR: unable to open $options{prefix}/tomcat-${instance_name}/webapps/ROOT/robots.txt for write.\n";
      exit 1;
    };
    print ROBOTS_TXT $collector_config->{robots};
    close ROBOTS_TXT;
  }
}

sub maybe_configure_tmpwatch {
  my ($instance_name, $config_name, $collector_config) = @_;
  if ($collector_config->{access_log}) {
    print STDERR "INFO: Configuring /etc/cron.daily/gratia-tmpwatch to clean up access.log files.\n";
    open(GRATIA_TMPWATCH, ">/etc/cron.daily/gratia-tmpwatch") or do {
      print STDERR "ERROR: unable to configure gratia-tmpwatch for access.log files: permissions?\n";
      exit 1;
      };
    print GRATIA_TMPWATCH <<EOF;
#!/bin/bash

flags=-m

/usr/sbin/tmpwatch "\$flags" 720 $options{prefix}/tomcat-${instance_name}/logs/access
EOF
    close GRATIA_TMPWATCH;
  } else {
    system("rm -f /etc/cron.daily/gratia-tmpwatch");
  }

}

sub maybe_restrict_services {
  my ($instance_name, $config_name, $collector_config) = @_;
  if (!$collector_config->{want_reporting}) {
    remove_services($instance_name, $config_name, $collector_config, @reporting_wars);
  } elsif (lc $collector_config->{want_reporting} eq "redirect") {
    install_urlrewrite($instance_name, $config_name, $collector_config, "reporting");
  } elsif (!$collector_config->{want_collector}) {
    remove_services($instance_name, $config_name, $collector_config, @collector_wars);
  }
}

sub install_urlrewrite {
  my ($instance_name, $config_name, $collector_config, @services) = @_;
  my ($urlrewrite_pkg, @dummy) = glob "$gratia_dir/urlrewrite*.zip";
  unless ($urlrewrite_pkg and -f $urlrewrite_pkg) {
    print STDERR "INFO: unable to find urlrewrite package in $gratia_dir: looking on tuckey.org ...\n";
    $urlrewrite_pkg=`wget -q -O - 'http://tuckey.org/urlrewrite/' | sed -ne 's/^.*"\\([^"]*dist\\/urlrewritefilter-[^"]*\\.zip\\)".*\$/\\1/p' | grep -v src`;
    chomp $urlrewrite_pkg;
    unless ($urlrewrite_pkg) {
      print STDERR "ERROR: unable to ascertain location of urlrewrite\n";
      exit 1;
    }
    system("cd $gratia_dir; wget -q \"$urlrewrite_pkg\"");
    ($urlrewrite_pkg,@dummy) = glob "$gratia_dir/urlrewrite*.zip";
    unless (-f $urlrewrite_pkg) {
      print STDERR "ERROR: unable to obtain urlrewrite package\n";
      exit 1;
    }
  }
  foreach my $service (@services) {
    next unless $service;
    print STDERR "INFO: Installing urlrewrite for $service service\n";
    my $war = "$options{prefix}/tomcat-${instance_name}/webapps/gratia-$service.war";
    my $service_dir = "$options{prefix}/tomcat-${instance_name}/webapps/gratia-$service";
    next unless (-f $war or -d $service_dir);
    if (-f $war) {
      unless (system("type jar >/dev/null 2>&1") == 0) {
        print STDERR "ERROR: unable to find jar executable to expand new service war\n";
        exit 1;
      }
      unless (system("rm -rf \"$service_dir\"") == 0) {
        print STDERR "ERROR: unable to remove $service_dir in order to expand new service\n";
        exit 1;
      }
      unless (system("mkdir -p \"$service_dir\" && cd \"$service_dir\" && jar xf \"$war\"") == 0) {
        print STDERR "ERROR: unable to expand new service war $war\n";
        exit 1;
      }
    }
    unless (system("cd \"$service_dir\" && unzip -q $urlrewrite_pkg") == 0) {
      print STDERR "ERROR: unable to expand urlrewrite package\n";
      exit 1;
    }
    open(WEBXML, "$service_dir/WEB-INF/web.xml") or do {
      print STDERR "ERROR: unable to find web.xml in $service_dir/WEB-INF/\n";
      exit 1;
    };
    my $webxml = join("", <WEBXML>);
    close(WEBXML);
    $webxml =~ s&(<web-app.*?>.*?\n)&$1
  <!-- UrlRewriteFilter configuration -->
  <filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
    <init-param>
      <param-name>logLevel</param-name>
      <param-value>WARN</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


&so;
    open(WEBXML, ">$service_dir/WEB-INF/web.xml") or do {
      print STDERR "ERROR: unable to write amended web.xml in $service_dir/WEB-INF/";
      exit 1;
    };
    print WEBXML $webxml;
    close(WEBXML);
    open(URLXML, "$service_dir/WEB-INF/urlrewrite.xml") or do {
      print STDERR "ERROR: unable to find urlrewrite.xml in $service_dir/WEB-INF/\n";
      exit 1;
    };
    my $urlxml = join("", <URLXML>);
    close(URLXML);
    my ($shorthost, $domain) = ($collector_config->{collector_host} =~ m&^([^\.]+)(.*)&);
    $urlxml =~ s&(<urlrewrite>.*?\n)&$1

  <rule enabled="true"> <!-- Controlled by REDIRECT_REPORTING in service start -->
    <note>
      This rule should redirect all reporting to the correct reporting service.
    </note>
    <from>/(.*)</from>
    <to type="permanent-redirect">http://${shorthost}-reports${domain}:$collector_config->{http_port}/gratia-reporting/\$1</to>
  </rule>
&so;
    open(URLXML, ">$service_dir/WEB-INF/urlrewrite.xml") or do {
      print STDERR "ERROR: unable to write amended urlrewrite.xml in $service_dir/WEB-INF/\n";
      exit 1;
    };
    print URLXML $urlxml;
    close(URLXML);
  }
}

sub remove_services {
  my ($instance_name, $config_name, $collector_config, @services) = @_;
  foreach my $service (@services) {
    next unless $service;
    my $war = "$options{prefix}/tomcat-${instance_name}/webapps/gratia-$service.war";
    my $service_dir = "$options{prefix}/tomcat-${instance_name}/webapps/gratia-$service";
    next unless (-f $war or -d $service_dir);
    print STDERR "INFO: Removing unneeded service, \"$service\"\n";
    if (system("rm -rf \"$war\" \"$service_dir\"") != 0) {
      print STDERR "ERROR: Unable to remove unwanted service $service from $options{prefix}/tomcat-${instance_name}/webapps\n";
      exit 1;
    }
  }
}

#--------------------------------------
sub configure_apel_directory {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $type = "APEL interfaces folder -";
  print STDERR "INFO: $type starting\n"; 
  my $apel       = $collector_config->{"properties.attributes"}->{"service.reporting.interfaces.apel.folder"};
  my $apel_group = $collector_config->{"properties.attributes"}->{"service.reporting.interfaces.apel.folder.groupowner"};
  unless ( defined $apel ) {
    print STDERR "INFO: $type not required.\n";
    print STDERR "INFO: $type complete\n"; 
    return 1;
  }
  unless ( defined $apel_group ) {
    print STDERR "ERROR: $type requested but no service.reporting.interfaces.apel.folder.groupowner specified.\n";
    exit 1;
  }
  my $data_directory = "$options{prefix}/tomcat-${instance_name}/webapps/$apel";
  if ( -d $data_directory ) { 
    print STDERR "INFO: $type already exists - $data_directory \n"; 
  } else {
    print STDERR "INFO: $type creating directory - $data_directory\n";
    eval ( mkpath($data_directory) );
    if ($@) {
      print  STDERR "ERROR: $type Failed to make directory - $data_directory\n"; exit 1;
    }
  }
  print STDERR "INFO: $type setting permissions(0775) on $data_directory\n";
  chmod 0775, $data_directory;
  #-- change group --
  print STDERR "INFO: $type setting group($apel_group) on $data_directory\n";
  my $gid = getgrnam($apel_group);
  unless ( defined $gid ) {
    print  STDERR "ERROR: $type group ($apel_group) not in /etc/group file\n";exit 1;
  } 
  my $status = system("chgrp -R $apel_group $data_directory");
  if ($status != 0) {
    print STDERR "ERROR: $type failed changing group ($apel_group) of $data_directory\n"; exit 1
  }
  #-- change permissions --
  $status = system("chmod -R g+w $data_directory");
  if ($status != 0) {
    print STDERR "ERROR: $type failed changing permissions of $data_directory files\n"; exit 1
  } 
  print STDERR "INFO: $type complete\n"; 
}

  sub configure_post_install {
    my ($instance_name, $config_name, $collector_config) = @_;
    my $post_file = "$options{prefix}/tomcat-${instance_name}/gratia/post-install";
    my $new_post = temporary_filename("post-install");
    $options{"db-root"} = "" unless exists $options{"db-root"};
    open(ORIG_POST, "<$post_file") or die "Unable to open $post_file for reading";
    open(NEW_POST, ">$new_post") or die "Unable to open $new_post for writing";
    chmod 0700, $new_post;
    $collector_config->{"PostInstallCmdPreamble"} =~
      s&DB_HOST&$collector_config->{"db_host"}&g
        if $collector_config->{"PostInstallCmdPrefix"};
    $collector_config->{"PostInstallCmdPrefix"} =~
      s&DB_HOST&$collector_config->{"db_host"}&g
        if $collector_config->{"PostInstallCmdPrefix"};
    while (<ORIG_POST>) {
      chomp;
      s&\${VDT_LOCATION}/mysql5/bin/&&; # VDT-specific location.
      s&\${VDT_LOCATION}/tomcat/v55/gratia/&$options{prefix}/tomcat-${instance_name}/gratia/&; # VDT-specific location.
      s&CMD_PREAMBLE&$collector_config->{"PostInstallCmdPreamble"}&;
      s&localhost&$collector_config->{"db_host"}&;
      s&(^.*?mysql.*?)CMD_SUFFIX(.*$)&$1$collector_config->{"PostInstallCmdSuffix"}$2&;
      s&(^.*?mysql.*?)ROOTPASS(.*$)&$1"$options{"db-root"}"$2&; # DB root password
      s&(^.*?mysql.*?)PORT(.*$)&$1$collector_config->{db_port}$2&; # DB port
      s&(^.*?mysql.*?--port=\d+\s+)\S+\s+(.*$)&$1 $collector_config->{db_schema} $2&; # Schema
      s&(^.*?)MAGIC_VDT_LOCATION/tomcat/v55/(.*$)&$1$options{prefix}/tomcat-${instance_name}/$2&; # Tomcat top dir
      # Extra commands to prefix mysql command (eg ssh, echo);
      s&^(.*?)CMD_PREFIX(.*$)&$1$collector_config->{"PostInstallCmdPrefix"}$2&;
      print NEW_POST "$_\n";
    }
    close(ORIG_POST);
    close(NEW_POST);
    system("mv -bv \"$new_post\" \"$post_file\"");
  }

sub configure_init_file {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $init_dir = "/etc/rc.d/init.d/";
  my $init_script = "$init_dir/tomcat-$instance_name";
  my $init_script_txt = $init_script_template;
  $init_script_txt =~ s&^(\s*CATALINA_OPTS\s*=\s*".*?)"&${1} -Xmx$collector_config->{max_heap_size}"&m if $collector_config->{max_heap_size};
  $init_script_txt =~ s&^(\s*CATALINA_OPTS\s*=\s*".*?)"&${1} -Xms$collector_config->{initial_heap_size}"&m if $collector_config->{inital_heap_size};
  $init_script_txt =~ s&^(\s*CATALINA_OPTS\s*=\s*".*?)"&${1} -XX:MaxPermSize=$collector_config->{max_perm_size}"&m if $collector_config->{max_perm_size};
  $init_script_txt =~ s&^(\s*CATALINA_OPTS\s*=\s*".*?)"&${1} -XX:PermSize=$collector_config->{initial_perm_size}"&m if $collector_config->{initial_perm_size};
  $init_script_txt =~ s&^(\s*CATALINA_OPTS\s*=\s*".*?)"&${1} -Djava.library.path=$collector_config->{tomcat_native_lib}"&m if $collector_config->{tomcat_native_lib};
  $init_script_txt =~ s&^(JAVA_HOME=).*$&${1}"$options{"java-home"}"&m;
  $init_script_txt =~ s&^(TOMCAT_HTTP_PORT=).*$&${1}$collector_config->{http_port}&m;
  $init_script_txt =~ s&^(TOMCAT_PATH_STEM=).*$&${1}"$options{prefix}"&m;
  $init_script_txt =~ s&^(TOMCAT_SSL_PORT=).*$&${1}$collector_config->{ssl_port}&m if $collector_config->{ssl_port};
  $init_script_txt =~ s&^(JSVC=).*$&${1}"$collector_config->{jsvc}"&m if $collector_config->{jsvc};
  $init_script_txt =~
    s&^(TOMCAT_USER=).*$&${1}$collector_config->{tomcat_user}&m
      if $collector_config->{tomcat_user};
  $init_script_txt =~ s&\^\^\^HOST_CERT\^\^\^&$collector_config->{host_cert}&;
  $init_script_txt =~ s&\^\^\^HOST_KEY\^\^\^&$collector_config->{host_key}&;
  my $redirect_val = ($collector_config->{want_reporting} and lc $collector_config->{want_reporting} eq "redirect")?"true":"false";
  $init_script_txt =~ s&^(REDIRECT_REPORTING=).*$&${1}"$redirect_val"&m;
  open(INIT_SCRIPT, ">$init_script") or die("Unable to open $init_script for writing");
  print INIT_SCRIPT $init_script_txt;
  close(INIT_SCRIPT);
  chmod 0755, $init_script;
  if ($collector_config->{want_reporting} and $collector_config->{want_reporting} eq "redirect") {
    # Want to be able to start with redirect off.
    system("cd $init_dir && rm -f tomcat-$instance_name-all && ln -s tomcat-$instance_name tomcat-$instance_name-all");
  } else {
    # Remove any vestigial -all startup script.
    system("cd $init_dir && rm -f tomcat-$instance_name-all");
  }
  if ($collector_config->{service_auto_start}) {
    system("/sbin/chkconfig --add tomcat-$instance_name");
  } else { # De-activate.
    system("/sbin/chkconfig --del tomcat-$instance_name");
  }
}

sub configure_collector_config {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $orig_config = "$options{prefix}/tomcat-${instance_name}/gratia/service-configuration.properties";
  my $config_name_file = temporary_filename("service-configuration.properties");
  open(ORIG_CONFIG, "<$orig_config") or die "Unable to open $orig_config for reading";
  open(REPORTING_CONFIG, ">$config_name_file") or die "Unable to open $config_name_file for writing";
  chmod 0600, $config_name_file;
  my %seen_attributes = ();
  my $in_summary_comment;
  my $spaced_rmi_port = sprintf("%5d", $collector_config->{rmi_port});
  my $spaced_http_port = sprintf("%5d", $collector_config->{http_port});
  my $spaced_ssl_port = $collector_config->{ssl_port}?sprintf("%5d", $collector_config->{ssl_port}):" n/a";
  my $spaced_db_port = sprintf("%5d", $collector_config->{db_port});

  foreach my $config_name_attribute (sort keys %{$collector_config->{"properties.attributes"}}) {
    # Code substitutions
    if (ref($collector_config->{"properties.attributes"}->{$config_name_attribute}) eq "CODE") {
      $collector_config->{"properties.attributes"}->{$config_name_attribute} =
        $collector_config->{"properties.attributes"}->{$config_name_attribute}($instance_name, $config_name, $collector_config);
    }
  }

  # Compound attributes and those using common attributes (eg http_port).
  $collector_config->{"properties.attributes"}->{"service.reporting.menuconfig"} =
    "$collector_config->{UserConfigPath}$collector_config->{UserConfig}";
  $collector_config->{"properties.attributes"}->{"service.rmi.port"} =
    "$collector_config->{rmi_port}";
  $collector_config->{"properties.attributes"}->{"service.rmi.rmibind"} =
    "//localhost:$collector_config->{rmi_port}";
  $collector_config->{"properties.attributes"}->{"service.rmi.rmilookup"} =
    "rmi://localhost:$collector_config->{rmi_port}";
  $collector_config->{"properties.attributes"}->{"service.open.connection"} =
    "http://$collector_config->{collector_host}:$collector_config->{http_port}"
      unless exists $collector_config->{"properties.attributes"}->{"service.open.connection"};
  $collector_config->{"properties.attributes"}->{"service.secure.connection"} =
    "https://$collector_config->{collector_host}:$collector_config->{ssl_port}"
      unless exists $collector_config->{"properties.attributes"}->{"service.secure.connection"};
  $collector_config->{"properties.attributes"}->{"service.mysql.url"} =
    "jdbc:mysql://$collector_config->{db_host}:$collector_config->{db_port}/$collector_config->{db_schema}";

  while (<ORIG_CONFIG>) {
    chomp;
    # Settings summary comment at top of file.
    m&^\s*#\s*default ports used by& and $in_summary_comment = 1;
    if ($in_summary_comment) {
      m&^\s*[^#]& and undef $in_summary_comment;
      s&^(\s*#\s)\s*\d*\s*(->\s*rmi)&${1}$spaced_rmi_port ${2}&;
      s&^(\s*#\s)\s*\d*\s*(->\s*tomcat)&${1}$spaced_http_port ${2}&;
      s&^(\s*#\s)\s*\d*\s*(->\s*tomcat-ssl)&${1}$spaced_ssl_port ${2}&;
      s&^(\s*#\s)\s*\d*\s*(->\s*mysql)&${1}$spaced_db_port ${2}&;
    }

    # Simple attributes
    foreach my $config_name_attribute (sort keys %{$collector_config->{"properties.attributes"}}) {
      $config_name_attribute =~ m/\.\d+$/ and next; # Special numbered item
        s&^(?:\s*###\s*)?(\Q$config_name_attribute\E\s*=\s*).*$&${1}$collector_config->{"properties.attributes"}->{$config_name_attribute}& and
          $seen_attributes{$config_name_attribute} = 1;
    }

    # Special case for multi-value configuration options -- group
    # similar numbered items together and dump items not wanted from the
    # config.
    if (m&^\s*(###\s*)?((\Qmonitor.to.address\E|\Qservice.admin.DN\E|\Qservice.admin.FQAN\E)\.\d+)&) {
      my ($prefix, $property, $base) = ($1 || '', $2, $3);
      next if ($seen_attributes{$base}); # Only print one set.
      $seen_attributes{$base} = 1;
      foreach my $numbered_attribute (sort(grep /^$base/,
                                           keys %{$collector_config->{"properties.attributes"}})) {
        next if $seen_attributes{$numbered_attribute};
        my $new_line = sprintf("$numbered_attribute = %s\n",
                               $collector_config->{"properties.attributes"}->{$numbered_attribute});
        # print "$_ -> ", $new_line;
        print REPORTING_CONFIG $new_line;
        $seen_attributes{$numbered_attribute} = 1;
      }
      next; # Don't print the line that triggered it.
    }
    print REPORTING_CONFIG "$_\n";
  }
  close(ORIG_CONFIG);
  # Simple attributes which may not already have been in the configuration file (eg monitor.to.address.N)

  foreach my $config_name_attribute (sort keys %{$collector_config->{"properties.attributes"}}) {
    print REPORTING_CONFIG "$config_name_attribute=",
      $collector_config->{"properties.attributes"}->{$config_name_attribute}, "\n"
        unless $seen_attributes{$config_name_attribute};
  }
  close(REPORTING_CONFIG);
  system("mv -bv \"$config_name_file\" \"$orig_config\"");
}

sub configure_keyfile_owners {
  my ($instance_name, $config_name, $collector_config) = @_;
  configure_host_keyfile_owner($instance_name, $config_name, $collector_config);
  configure_http_keyfile_owner($instance_name, $config_name, $collector_config);
}

sub configure_host_keyfile_owner {
  my ($instance_name, $config_name, $collector_config) = @_;
  return unless exists $collector_config->{"host_key"};
  configure_keyfile_owner($instance_name, $config_name, $collector_config,
                          "configuration attribute host_key",
                          \$collector_config->{"host_key"});
}

sub configure_http_keyfile_owner {
  my ($instance_name, $config_name, $collector_config) = @_;
  return unless exists $collector_config->{"properties.attributes"}->{"service.vdt.key.file"};
  configure_keyfile_owner($instance_name, $config_name, $collector_config,
                          "service-configuration.properties attribute service.vdt.key.file",
                          \$collector_config->{"properties.attributes"}->{"service.vdt.key.file"});
}

sub configure_keyfile_owner {
  my ($instance_name, $config_name, $collector_config, $key_message, $key_ref) = @_;
  if (exists $collector_config->{"tomcat_user"}) {
    if ($$key_ref and -e $$key_ref) {
      print STDERR "TOMCAT_USER specified as ",
        $collector_config->{"tomcat_user"},
          ": verifying readable copy of key at $$key_ref for $key_message ...\n";
      my (@temp) = stat($$key_ref);
      @temp = getpwuid($temp[4]);
      my $user = $temp[0] || $temp[4];
      print STDERR "DEBUG: Extracted user name $user as owner of $$key_ref\n";
      if ($user ne
          $collector_config->{"tomcat_user"}) {
        print STDERR "Producing copy of key file readable by $$key_ref ...\n";
        my ($path, $basename, $ext) = ($$key_ref =~ m&^(.*/)?([^\.]*)(.*)$&);
        $path = "" unless defined $path;
        $basename = "" unless defined $basename;
        $ext = "" unless defined $ext;
        print STDERR "DEBUG: deconstructed $$key_ref to ($path, $basename, $ext).\n";
        $basename = "$basename-$collector_config->{\"tomcat_user\"}";
        my $orig_key = $$key_ref;
        $$key_ref = "$path$basename$ext";
        if (system("install -o $collector_config->{\"tomcat_user\"} -m 600 \"$orig_key\" \"$$key_ref\"") == 0) {
          print STDERR "Successfully copied \"$orig_key\" to \"$$key_ref\"\n";
        } else {
          print STDERR "ERROR: could not create copy of key readable by ",
            "$collector_config->{\"tomcat_user\"} as $$key_ref -- you will need to do this ",
              "manually to match the personalized configuration\n";
        }
      }
    } else {
      print STDERR "Key not specified or does not point to real file!\n";
    }
  }
}

sub configure_installation_owner {
  my ($instance_name, $config_name, $collector_config) = @_;
  if (exists $collector_config->{"tomcat_user"}) {
    print STDERR "TOMCAT_USER specified as ",
      $collector_config->{"tomcat_user"},
        ": changing ownership of $options{prefix}/tomcat-${instance_name} ... ";
    my $group = ($collector_config->{"tomcat_group"})?sprintf(".%s", $collector_config->{"tomcat_group"}):"";
    my $status =
      system("chown -R $collector_config->{\"tomcat_user\"}${group} \"$options{prefix}/tomcat-${instance_name}/\"");
    if ($status == 0) {
      print STDERR "OK\n";
      system("chmod g+s \"$options{prefix}/tomcat-${instance_name}\"") if ${group};
    } else {
      print STDERR "FAILED!\n";
      print STDERR "ERROR changing ownership of ",
        "\"$options{prefix}/tomcat-${instance_name}\" ",
          "to $collector_config->{\"tomcat_user\"}${group}\n";
    }
  }
  # Configure ownership of the APEL interface directory.
  configure_apel_directory($instance_name, $config_name, $collector_config);
}

sub configure_tomcat_config {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $orig_config = "$options{prefix}/tomcat-${instance_name}/conf/server.xml";
  my $config_name_file = temporary_filename("server.xml");
  open(ORIG_CONFIG, "<$orig_config") or die "Unable to open $orig_config for reading";
  open(REPORTING_CONFIG, ">$config_name_file") or die "Unable to open $config_name_file for writing";
  chmod 0600, $config_name_file;
  my %seen_attributes = ();
  my $line_buffer = "";
  my $in_comment;
  my $in_catalina;
  my $in_connector;
  my $in_engine;
  my $seen_engine;
  while (<ORIG_CONFIG>) {
    next if m&<!-- Gratia connectors -->&; # Avoid comment build-up, floss regularly.
    $line_buffer = "${line_buffer}$_";
    $in_comment = 1 if (m&<!--&);
    if ($line_buffer =~ m&-->&) {
      undef $in_comment;
    }

    next if $in_comment;

    $line_buffer =~ s&(<Server\s+port\s*=\s*)"[^"]+"&${1}"$collector_config->{server_port}"&;

    $line_buffer =~ m&<\s*Service\s+name\s*=\s*"Catalina"\s*>\s*$& and $in_catalina = 1;

    if ($in_catalina and not $in_comment) {
      $line_buffer =~ m&^\s*<\s*Connector\s*& and $in_connector = 1;
      if ($in_engine) {
        next unless $line_buffer =~ m&/\s*Engine\s*>&;
        undef $in_engine;
        # Remove existing FastCommonAccessLogValves *only*
        $line_buffer =~ s&\n[ \t]*<\s*Valve[^>]*?\Q"org.apache.catalina.valves.FastCommonAccessLogValve"\E.*?\s*/\s*>\s*?&&sg;
        # Put optinal new one in.
        if ($collector_config->{access_log}) {
          my $insert_valve = <<EOF;
        <Valve className="org.apache.catalina.valves.FastCommonAccessLogValve"
               directory="logs/access"
               prefix="access.log."
               resolveHosts="false"
               rotatable="true"
               fileDateFormat="yyyy-MM-dd"/>
EOF
          $line_buffer =~ s&^(\s*<\s*Engine.*?>.*?\n)&$1$insert_valve&s;
        }
      }
      if ($in_connector) {
        next unless $line_buffer =~ m&/\s*>&;
        undef $in_connector;
        $line_buffer =~ s&<\s*Connector.*\s*/\s*>(?:\s*$)?&&s;
      }
      if (not $seen_engine and not $in_engine and $line_buffer =~ m&^\s*<\s*Engine&) {
        $in_engine = $seen_engine = 1;
        print REPORTING_CONFIG <<EOF;
    <!-- Gratia connectors -->
    <Connector port="$collector_config->{http_port}" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false"
EOF
        print REPORTING_CONFIG <<EOF if $collector_config->{ssl_port};
               redirectPort="$collector_config->{ssl_port}"
EOF
        print REPORTING_CONFIG <<EOF;
               acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" />
EOF
        print REPORTING_CONFIG <<EOF if $collector_config->{ssl_port};
    <Connector port="$collector_config->{ssl_port}"
               maxHttpHeaderSize="8192"
               maxThreads="150"
               minSpareThreads="25"
               maxSpareThreads="75"
               enableLookups="false"
               disableUploadTimeout="true"
               acceptCount="100"
               debug="0"
               scheme="https"
               secure="true"
               sSLImplementation="net.sf.gratia.trustmanager.GratiaTMSSLImplementation"
               sslCAFiles="$collector_config->{sslCAFiles}"
               crlFiles="$collector_config->{crlFiles}"
               sslCertFile="$collector_config->{host_cert}"
               sslKey="$collector_config->{host_key}"
               clientAuth="true"
               sslProtocol="TLS"
               crlEnabled="true"
               crlRequired="false"/>
EOF
        #               keystoreFile="$options{prefix}/tomcat-${instance_name}/gratia/keystore" keystorePass="server"
        #               truststoreFile="$options{prefix}/tomcat-${instance_name}/gratia/truststore" truststorePass="server"
        #               log4jConfFile="$options{prefix}/tomcat-${instance_name}/conf/log4j-trustmanager.properties"
        next; # Accumulate line buffer.
      }
    }
    print REPORTING_CONFIG "$line_buffer";
    $line_buffer = "";
  }
  close(ORIG_CONFIG);
  close(REPORTING_CONFIG);
  system("mv -bv \"$config_name_file\" \"$orig_config\"");
}

sub configure_name_file {
  my ($instance_name, $config_name, $collector_config) = @_;
  open(NAME_FILE, ">$options{prefix}/tomcat-${instance_name}/collector-host.txt")
    or die "Unable to open $options{prefix}/tomcat-${instance_name}/collector-host.txt for write!";
  print NAME_FILE $collector_config->{collector_host}, "\n";
  close(NAME_FILE);
  open(NAME_FILE, ">$options{prefix}/tomcat-${instance_name}/collector-config-name.txt")
    or die "Unable to open $options{prefix}/tomcat-${instance_name}/collector-config-name.txt for write!";
  print NAME_FILE $config_name, "\n";
  close(NAME_FILE);
}

sub configure_tomcat_users {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $config_name_file = "$options{prefix}/tomcat-${instance_name}/conf/tomcat-users.xml";
  open(CONFIG_SCRIPT, ">$config_name_file") or die("Unable to open $config_name_file for writing");
  chmod 0600, $config_name_file;
  print CONFIG_SCRIPT $tomcat_users_txt;
  close(CONFIG_SCRIPT);
}

sub construct_monitor_message_subject {
  my ($instance_name, $config_name, $collector_config) = @_;
  return sprintf("%s:%s %s (\"%s\") Potential recordProcessor problem",
                 $collector_config->{collector_host},
                 $collector_config->{http_port},
                 "tomcat-$instance_name",
                 $config_name
                );
}

sub temporary_filename {
  my $stem = shift;
  my $tmp_file=`mktemp "\${TMPDIR:-/tmp}/${stem}_XXXXXXXXXX\"`;
  chomp $tmp_file;
  $tmp_file or die "Unable to create temporary file from stem $stem";
  return $tmp_file;
}

sub configure_static_report_generation {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $wantStatic =
    ($collector_config->{staticReports} =~ /(?:t|true|1)/i);
  my $removeOrTime = ($wantStatic)?
    "CRON_TIMING=\"42 0 * * *\"":
      "CRON_REMOVE=1";
  my $static_report_generator = "$options{prefix}/tomcat-${instance_name}/gratia/staticReports.py";
  return unless (-x $static_report_generator);
  my @script_pars = ("$options{prefix}/tomcat-${instance_name}",
                     sprintf("%s%s:%s/gratia-reporting/",
                             "http://",
                             $collector_config->{collector_host},
                             $collector_config->{http_port}));
  print STDERR "INFO: ",
    ($wantStatic?
     "configuring static reports":
     "removing any existing static report generation"),
       "\n";
  system(sprintf("VISUAL=${gratia_dir}/safe-replace-crontab $removeOrTime CRON_CMD=\"'$static_report_generator' %s >/dev/null 2>&1\" crontab -e",
                 join(" ", map { "'$_'"; } @script_pars)));
}

sub verify_remote_host_setting {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $remote_host;
  if ($options{"remote-host"}) {
    print STDERR "INFO: overriding instance-specified remote hostname with command-line-specified $options{\"remote-host\"}\n";
    $remote_host = $options{"remote-host"};
  } elsif ($collector_config->{remote_host}) {
    print STDERR "INFO: using instance-specified remote hostname ",
      $collector_config->{remote_host}, "\n";
    $remote_host = $collector_config->{remote_host};
  } else {
    print STDERR "INFO: using default remote hostname $default_remote_host\n";
    $remote_host = $default_remote_host;
  }
  # Propagate back for consistency
  $collector_config->{remote_host} = $remote_host;
  $collector_config->{collector_host} =
    ( $collector_config->{remote_host} || "localhost" )
      unless exists $collector_config->{collector_host};
}

sub wants_config_info {
  return 1 if ($options{"print-config"} ||
               $options{"obtain-config-item"} ||
               $options{"obtain-properties-item"});
}

sub maybe_print_config_info {
  my ($instance_name, $config_name, $collector_config) = @_;
  my $want_info = 0;
  if ($options{"print-config"}) {
    foreach my $item (sort keys %{$collector_config}) {
      next if $item eq "properties.attributes";
      $want_info = 1;
      print "config: ",
        $item,
          " = ",
            $collector_config->{$item},
              "\n";
    }
    foreach my $item (sort keys %{$collector_config->{"properties.attributes"}}) {
      print "property: ",
        $item,
          " = ",
            $collector_config->{"properties.attributes"}->{$item},
              "\n";
    }
  } else {
    if ($options{"obtain-config-item"} and scalar @{$options{"obtain-config-item"}}) {
      $want_info = 1;
      foreach my $item (@{$options{"obtain-config-item"}}) {
        if (exists ($collector_config->{$item})) {
          print "config: ",
            $item,
              " = ",
                $collector_config->{$item},
                  "\n";
        }
      }
    }
    if ($options{"obtain-properties-item"} and scalar @{$options{"obtain-properties-item"}}) {
      $want_info = 1;
      foreach my $item (@{$options{"obtain-properties-item"}}) {
        if (exists ($collector_config->{"properties.attributes"}->{$item})) {
          print "property: ",
            $item,
              " = ",
                $collector_config->{"properties.attributes"}->{$item},
                  "\n";
        }
      }
    }
  }
  return $want_info;
}


use File::Find;
my (@found_files, $list_file);
sub wanted {
  # print STDERR "File::Find::dir = $File::Find::dir\n";
  if ($File::Find::name =~ m&gratia/data/(?:history-|old-|thread)&) {
    # print STDERR "File::Find: pruning search tree\n";
    $File::Find::prune = 1;
    return;
  }
  if (-d $_) {
    # print STDERR "File::Find: looking in $File::Find::name ...\n";
    if (-f "$_/$list_file") {
      # print STDERR "File::Find found $File::Find::name/$list_file";
      push @found_files, "$File::Find::name/$list_file";
      $File::Find::prune = 1;
    } elsif (-f "$_/$list_file.dat") { # Default extension
      # print STDERR "File::Find found $File::Find::name/$list_file.dat";
      push @found_files, "$File::Find::name/$list_file.dat";
      $File::Find::prune = 1;
    }
  }
}

sub find_dat_file {
  $list_file = shift;
  @found_files = ();
  my @search_path = ( "$gratia_dir", @_ );
  chomp $list_file;
  if ( -f $list_file ) {
    if ($list_file =~ m&/&) {
      my ($file, $dir) = fileparse($list_file);
      $dir=`cd "$dir" && /bin/pwd`;
      chomp $dir;
      $list_file="$dir/$file";
    } else {
      my $dir = `/bin/pwd`;
      chomp $dir;
      $list_file="$dir/$list_file";
    }
  } else {
    my @dir_list = map { (-d)?$_:() } @search_path;
    #    print STDERR "Looking for $list_file, dir list = ", join(", ", @dir_list), "\n";
    find ( \&wanted, @dir_list );
    # First found in search path order.
    $list_file = $found_files[0] if scalar @found_files;
  }
  return $list_file;
}

__END__
########################################################################
# Plain old documentation
########################################################################

=pod

=head1 NAME

configure-collector: Configure a Gratia / Tomcat instance.

=head1 SYNOPSIS

B<configure-collector> B<-h> | B<--help> | B<-?>

B<configure-collector> B<--print-config> [--] I<instance>

B<configure-collector> B<--obtain-config-item> I<item>+ |& B<--obtain-properties-item> I<item>+ [--] I<instance>

B<configure-collector> [I<global-options>] [--] I<instance>+

I<global-options>: B<-r> I<collector-host-name> | B<--remote-host> I<collector-host-name> |
                 B<-j> I<JRE-home-dir> | B<--java-home> I<JRE-home-dir> |
                 B<-p> I<install-path-prefix> | B<--prefix> I<install-path-prefix> |
                 B<--db-root> I<db-root-pword> | B<-d> I<db-root-dir> |
                 B<--collector-info> I<collector-dat-file> | B<-c> I<collector-dat-file> |

Options marked with B<+> are repeatable and cumulative.

=head1 DESCRIPTION

I<configure-collector> is a tool to configure one or more gratia instances.

I<configure-collector> can only configure instances about which it
already knows: please look at the B<%collector_configs> associative
array for details.

=head2 OPTIONS

=over 4

=item B<-r> I<collector-host-name>

=item B<--remote-host> I<collector-host-name>


The remote hostname of the collector (eg gratia-osg.fnal.gov).


=item B<-j> I<JRE-home-dir>

=item B<--java-home> I<JRE-home-dir>


The location of a Java-1.5 runtime.


=item B<-p> I<install-path-prefix>

=item B<--prefix> I<install-path-prefix>


The directory above the tomcat instance (eg /scratch).


=item B<--db-root> I<db-root-pword>

=item B<-d> I<db-root-pword>


The DB (not system) root password.


=item B<--print-config>


Print the full configuration for the first chosen instance. Does not continue
with the install. Other instances are ignored.


=item B<--obtain-config-item> I<item>

=item B<--print-config-item> I<item>


Print the specified configuration item to be used for the first chosen
instance. Does not continue with the install. Other instances are ignored.


=item B<--obtain-properties-item> I<item>

=item B<--print-properties-item> I<item>

=item B<--print-property> I<item>


Print the specified service-configuration.properties item to be used for
the first chosen instance. Does not continue with the install. Other
instances are ignored.


=head1 AUTHOR

Chris Green <greenc@fnal.gov>.

=cut

### Local Variables:
### mode: cperl
### End:
