#!/usr/bin/env bash

if variable_is_empty init_scripts_path
then
  init_scripts_path="$(init_scripts_path)"
fi

if variable_is_empty confd_path
then
  confd_path="$(confd_path)"
fi

# TODO: Account for user service installs...
# TODO: Merge service_paths and service_root_paths...

# TODO: determine root_install vs user_install...
if user_is_root
then
  etc_path="/etc"
  var_path="/var"
else
  etc_path="${packages_path}/active/etc"
  var_path="${packages_path}/active/var"
fi

: \
  "${service:="${extension}"}" \
  "${service_version:="${package_version}"}" \
  "${prefix_path:="${bdsm_path}/active"}" \
  "${service_bin_path:="${active_path}/bin"}" \
  "${service_sbin_path:="${active_path}/sbin"}" \
  "${service_pid_path:="${var_path}/run/${service}"}" \
  "${service_spool_path:="${var_path}/spool/${service}"}" \
  "${service_config_path:="${etc_path}/${service}"}" \
  "${service_db_path:="${var_path}/db/${service}"}" \
  "${service_data_path:="${var_path}/db/${service}/${package_version}"}" \
  "${service_log_path:="${var_path}/log/${service}"}" \
  "${service_lock_path:="${var_path}/lock/${service}"}" \
  "${service_src_path:="${source_path}/${service}-${package_version}"}" \
  "${service_config_file:="${service_config_path}/${service}.conf"}" \
  "${service_log_file:="${service_log_path}/${service}.log"}" \
  "${service_pid_file:="${service_pid_path}/${service}.pid"}" \
  "${service_lock_file:="${service_lock_path}/${service}.lock"}" \
  "${service_run_as_root_flag:=0}"

service_paths=(
  "${service_bin_path}"
  "${service_config_path}"
  "${service_pid_path}"
  "${service_spool_path}"
  "${service_data_path}"
  "${service_lock_path}"
  "${service_log_path}"
)

service_root_paths=(
  "${var_path}/spool/${service}"
  "${var_path}/log/${service}"
  "${var_path}/run/${service}"
  "${var_path}/lock/${service}"
  "${var_path}/db/${service}"
)

if user_is_root
then
  true "${service_user:="${package_user:-"${service}"}"}"
else
  true "${service_user:="${package_user:-"$USER"}"}"
fi

for _path in  "${install_path}/bin" "${install_path}/sbin"
do
  if path_exists "$_path"
  then
    export PATH="${_path}:$PATH"
  fi
done

if variable_is_empty service_binary
then
  if command_exists ${service}
  then
    service_binary="$(command -v ${service})"
  fi
fi

service_actions=( start stop restart )
service_flags=()
service_start_flags=()
service_stop_flags=()
service_restart_flags=()
service_status_flags=()
service_reload_flags=()

export service_paths service_actions service_flags

if file_is_nonempty "${service_pid_file}"
then
  read -r service_pid < "${service_pid_file}"
else
  service_pid=0
fi
