#!/bin/sh

## Make it so config files are not overwritten
config() {
  NEW="$1"
  OLD="`dirname $NEW`/`basename $NEW .new`"
  # If there's no config file by that name, mv it over:
  if [ ! -r $OLD ]; then
    mv $NEW $OLD
  elif [ "`cat $OLD | md5sum`" = "`cat $NEW | md5sum`" ]; then # toss the redundant copy
    rm $NEW
  fi
  # Otherwise, we leave the .new copy for the admin to consider...
}

## List of conf files to check.
config etc/rc.d/rc.tomcat.new
config etc/apache-tomcat/catalina.policy.new
config etc/apache-tomcat/catalina.properties.new
config etc/apache-tomcat/logging.properties.new
config etc/apache-tomcat/context.xml.new
config etc/apache-tomcat/server.xml.new
config etc/apache-tomcat/tomcat-users.xml.new
config etc/apache-tomcat/web.xml.new

check_tomcat_env() {
  def_uid=8080
  def_gid=8080
  TOMCAT_USER=tomcat
  TOMCAT_HOME="/usr/share/apache-tomcat"
  # Confirm that the 'tomcat' user and group exist.
  grep -q "^$TOMCAT_USER:" /etc/group || groupadd -g $def_gid $TOMCAT_USER || exit 1
  grep -q "^$TOMCAT_USER:" /etc/passwd || useradd -c "Apache Tomcat" -d $TOMCAT_HOME -g $TOMCAT_USER -u $def_uid $TOMCAT_USER || exit 1
}

check_tomcat_env
chown -R tomcat.tomcat /etc/apache-tomcat
chown -R tomcat.tomcat /var/cache/apache-tomcat
chown -R tomcat.tomcat /usr/share/apache-tomcat
chown -R tomcat.tomcat /var/lib/apache-tomcat
chown -R tomcat.tomcat /var/log/apache-tomcat
chown -R tomcat.tomcat /var/tmp/apache-tomcat

echo -e "\E[1;32m"
echo -e " In the file rc.tomcat additions variable optional JAVA_OPTS"
echo -e " (with a basic understanding), this prevents exception:\n"
echo -e "   java.lang.OutOfMemoryError: Java heap Space"
echo -e "\E[0m"

# Make symlinks (generated by makepkg)
( cd usr/share/apache-tomcat ; rm -rf conf )
( cd usr/share/apache-tomcat ; ln -sf /etc/apache-tomcat conf )
( cd usr/share/apache-tomcat ; rm -rf logs )
( cd usr/share/apache-tomcat ; ln -sf /var/log/apache-tomcat logs )
( cd usr/share/apache-tomcat ; rm -rf temp )
( cd usr/share/apache-tomcat ; ln -sf /var/tmp/apache-tomcat temp )
( cd usr/share/apache-tomcat ; rm -rf work )
( cd usr/share/apache-tomcat ; ln -sf /var/cache/apache-tomcat work )
( cd usr/share/apache-tomcat ; rm -rf webapps )
( cd usr/share/apache-tomcat ; ln -sf /var/lib/apache-tomcat webapps )
