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

v_fbsd_up_binary="/usr/sbin/freebsd-update"
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"


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_do () {
  log_start "fbsd_up_do"

  fbsd_up_init
  fbsd_up_versions
  {
    $v_fbsd_up_binary updatesready
    local _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

  log_end
}
