#!/bin/sh

# PROVIDE: puppetserver
# REQUIRE: LOGIN
# KEYWORD: shutdown

#
# Configuration settings for puppetserver in /etc/rc.conf:
#
# puppetserver_enable (bool):
#   Set to "NO" by default.
#   Set it to "YES" to enable puppetserver
#
# puppetserver_args (str):
#   Extra arguments passed to start command
#
# puppetserver_java_home (str):
#   Set to "%%JAVA_HOME%%" by default.
#   Set the Java virtual machine to run puppetserver
#
# puppetserver_java_opts (str):
#   Set to "" by default.
#   Java VM args to use.
#
# puppetserver_user (str):
#   Set to "puppet" by default.
#   User to run puppetserver as.
#
# puppetserver_group (str):
#   Set to "puppet" by default.
#   Group for data file ownership.
#
# puppetserver_log_file (str):
#   Set to "/var/log/puppetserver/puppetserver.log" by default.
#   Log file location.
#

. /etc/rc.subr

name="puppetserver"
rcvar=puppetserver_enable

load_rc_config "${name}"

: ${puppetserver_enable="NO"}
: ${puppetserver_args="--config %%PREFIX%%/etc/puppetserver/conf.d -b %%PREFIX%%/etc/puppetserver/services.d"}
: ${puppetserver_java_home="%%JAVA_HOME%%"}
: ${puppetserver_java_opts=""}
: ${puppetserver_user="puppet"}
: ${puppetserver_group="puppet"}
: ${puppetserver_log_file="/var/log/puppetserver/puppetserver.log"}

pidfile="/var/run/puppetserver/puppetserver.pid"
command="/usr/sbin/daemon"
java_cmd="${puppetserver_java_home}/bin/java"
procname="${java_cmd}"
command_args="-f -p ${pidfile} ${java_cmd} -Djruby.logger.class=com.puppetlabs.jruby_utils.jruby.Slf4jLogger -Dlogappender=F1 ${puppetserver_java_opts} -cp %%DATADIR%%/puppet-server-release.jar:%%PREFIX%%/lib/ruby/vendor_ruby/facter.jar clojure.main -m puppetlabs.trapperkeeper.main ${puppetserver_args}"


required_files="${java_cmd}"

start_precmd="puppetserver_prestart"

# An UTF-8 locale is required
: LC_ALL=${LC_ALL:=C.UTF-8}
case $LC_ALL in
    *.UTF-8)
        ;;
    *.*)
        LC_ALL="${LC_ALL%.*}.UTF-8"
        ;;
    *)
        LC_ALL=C.UTF-8
        ;;
esac
export LC_ALL

puppetserver_prestart() {
  if [ ! -f "${puppetserver_log_file}" ]; then
    touch "${puppetserver_log_file}"
    chown "${puppetserver_user}:${puppetserver_group}" "${puppetserver_log_file}"
    chmod 640 "${puppetserver_log_file}"
  fi
  if [ ! -d "/var/run/puppetserver" ]; then
    install -d -o "${puppetserver_user}" -g "${puppetserver_group}" -m 750 "/var/run/puppetserver"
  fi

  chown -R "root:${puppetserver_group}" "%%PREFIX%%/etc/puppetserver/conf.d"
  chmod 0750 "%%PREFIX%%/etc/puppetserver/conf.d"

  chown "root:${puppetserver_group}" "%%PREFIX%%/etc/puppetserver/logback.xml"
  chmod 0640 "%%PREFIX%%/etc/puppetserver/logback.xml"
}

run_rc_command "$1"
