#!/bin/sh
export PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin"
BIN_ROOT="$(dirname "$(readlink -f "$0")")"
APP_ROOT="$(dirname "$BIN_ROOT")"
STATE_ROOT="$APP_ROOT/var"

if ! [ -d "$STATE_ROOT" ]; then
  echo "NO STATE ROOT DIR: ${STATE_ROOT}" >&2
  exit 1
fi


cat /dev/null > "$STATE_ROOT/status"

. "$APP_ROOT/lib/log.sh"


if ! [ -f "$APP_ROOT/config.sh" ] ; then
  echo "UNCONFIGURED!!!!" >&2
  exit 1
fi

TMP_ROOT="$(mktemp -dqp /tmp aw-fbsd-monitoring-XXXXXXXXXXXX)"
_err_status=$?
if [ ${_err_status} -ne 0 ] ; then
  log_err -s "Cannot make TMP_ROOT, error status ${_err_status}"
  exit 1
fi

USER_MON_PKG_LIST="$TMP_ROOT/user_pkg_mon"
touch "${USER_MON_PKG_LIST}"

my_exit () {
  if [ -d "$TMP_ROOT" ] ; then
    rm -frv "$TMP_ROOT" 2>&1 | log
  fi
}

trap my_exit 0

. "$APP_ROOT/lib/common.sh"
. "$APP_ROOT/config.sh"
. "$APP_ROOT/lib/fbsd_up.sh"
. "$APP_ROOT/lib/pkg.sh"

log "Start process, but sleep some..."
sleep_some

{
  fbsd_up_do
  pkg_do
} 2>&1 | log_err -s 2>&1 | to_status
