#!/bin/sh
#

# PROVIDE: vast
# REQUIRE: NETWORKING
# REQUIRE: LOGIN FILESYSTEMS
# KEYWORD: shutdown

# Add these lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# vast_enable (bool): Set to YES to enable VAST
#                     Default: NO
# vast_config (path): Path to the VAST configuratio file
#                     Default: %%PREFIX%%/etc/vast/vast.yaml

. /etc/rc.subr

name="vast"
desc="Visibility Across Space and Time"
rcvar="${name}_enable"
start_precmd="${name}_prestart"
extra_commands="check"
check_cmd="${name}_check"

# Note that we cannot use the variables $vast_user and $vast_group because
# otherwise the rc script would drop privileges before invoking
# /usr/sbin/daemon.

# TODO: VAST currently does not handle the --config option properly, which is
# why we have a separate option ${vast_dir} to specificy the directory instead.

load_rc_config $name
: ${vast_enable:=NO}
: ${vast_config:=%%PREFIX%%/etc/${name}/${name}.yaml}
: ${vast_dir:=/var/db/${name}}
: ${vast_proc_user:=${name}}
: ${vast_proc_group:=${vast_proc_user}}
: ${vast_pidfile:=/var/run/${name}.pid}

pidfile="${vast_pidfile}"
required_files="${vast_config}"
vast_program="/usr/sbin/daemon"
vast_flags="-f -P ${pidfile} -r -u ${vast_proc_user}"
command_args="%%PREFIX%%/bin/${name} -d ${vast_dir} start"

vast_check()
{
  # Ensure VAST group exists.
  if ! pw groupshow ${vast_proc_group} > /dev/null 2>&1; then
    echo "Adding new group for VAST process: ${vast_proc_group}"
    pw groupadd ${vast_proc_group}
  fi
  # Ensure VAST user exists.
  if ! pw usershow ${vast_proc_user} > /dev/null 2>&1; then
    echo "Adding new user for VAST process: ${vast_proc_user}"
    pw useradd -n ${vast_proc_user} -g ${vast_proc_group} -c "VAST process account" \
      -d /dev/null -s /sbin/nologin -w no
  fi
  # Esnure VAST state directory has the right permissions.
  if [ ! -d "${vast_dir}" ]; then
    echo "Creating new VAST state dir: ${vast_dir}"
    mkdir -m 700 -p "${vast_dir}"
    chown "${vast_proc_user}:${vast_proc_group}" "${vast_dir}"
  fi
}

vast_prestart()
{
  run_rc_command check
}

run_rc_command "$1"
