#!/bin/sh
# Работа с обновлениями FreeBSD

v_fbsd_up_binary="/usr/sbin/freebsd-update --not-running-from-cron"
v_fbsd_up_out="$STATE_ROOT/fbsd_update"
v_fbsd_up_status="$STATE_ROOT/fbsd_update.status"
v_fbsd_up_current_ver="$STATE_ROOT/fbsd_update.versions"
v_fbsd_up_action_flag="$STATE_ROOT/fbsd_update.action.flag"


fbsd_up_init () {
  $v_fbsd_up_binary fetch > "$v_fbsd_up_out"
}


fbsd_up_status () {
  echo "$1" > "$v_fbsd_up_status"
}


fbsd_up_versions () {
  printf "userland=%s\nkernel=%s\nkcurrent=%s\n" \
    "$(/bin/freebsd-version -u)" \
    "$(/bin/freebsd-version -k)" \
    "$(/bin/freebsd-version -r)" \
    > "${v_fbsd_up_current_ver}"
}

fbsd_up_check_action_flag () {
  local res _act_flag

  res="$(( $(date '+%s') / 14400 ))"
  _act_flag="$(cat "$v_fbsd_up_action_flag")"

  if [ -z "$_act_flag" ] || [ "$res" -ne "$_act_flag"  ] ; then
    echo "$res" | tee "$v_fbsd_up_action_flag"
  fi
}


fbsd_up_do () {
  local _action_flag _ret

  log_start "fbsd_up_do"

  _action_flag="$(fbsd_up_check_action_flag)"
  if [ -z "$_action_flag" ] ; then
    log "Not need to update: old action mark"

  else
    log "New action flag '${_action_flag}' - updating"
    fbsd_up_init
    fbsd_up_versions
    {
      $v_fbsd_up_binary updatesready
      _ret="$?"

      case "$_ret" in
        0 )
          if [ "$(cat "$v_fbsd_up_status")" != "NEED UPDATE" ]; then
            mail -s "$(hostname -f): FREEBSD UPDATE NEEDED" "$ADMIN_MAIL" < "$v_fbsd_up_out"
          fi

          fbsd_up_status "NEED UPDATE"
        ;;

        1 )
          fbsd_up_status "RUN ERROR"
          ;;

        2 )
          fbsd_up_status "OK"
          ;;

        * )
          fbsd_up_status "RUN ERROR"
          log_err "fbsd_up: updatesready return unknown code ${_ret}"
          ;;
      esac
    } 2>&1 | log
  fi

  log_end
}
