#!/bin/sh
# Различная статистика по пакетам

v_pkg_detail_status="$STATE_ROOT/pkg_detail"
v_pkg_update_status="$STATE_ROOT/pkg_update"

pkg_init () {
  if ! [ -d "$v_pkg_detail_status" ]; then
    mkdir -p "$v_pkg_detail_status"
  else
    # Удаляем старые директории, в которые давно не не пишутся данные по пакетам
    log "Clean old detail pakages"
    find "$v_pkg_detail_status" -type f -ctime +1 -print0 | xargs -0n 1 rm -frv 2>&1 | log
  fi
  log "Update pakages"
  pkg update 2>&1 | log
  # Обновление базы аудита происходит на получении общих данных по пакетам
}

pkg_make_detail () {
  local vl_pkg_fullname
  local vl_pkg_repo
  local vl_pkg_name
  local vl_pkg_ver
  local vl_status_file
  local vl_pkg_status

  service -e | awk '$1 ~ "^/usr/local" {print $1}' | while read svc_file; do
      if ! [ -f "$svc_file" ] ; then
        continue
      fi

      vl_pkg_fullname="$(pkg which "$svc_file" | awk '$0 ~ "was installed by package" {print $6}')"
      if [ -z "$vl_pkg_fullname" ] ; then
        log "$svc_file have no matched pkg"
        continue
      fi

      vl_pkg_name="$(pkg query '%n' "$vl_pkg_fullname")"
      vl_pkg_repo="$(pkg query '%R' "$vl_pkg_fullname")"
      vl_pkg_ver="$(pkg query '%v' "$vl_pkg_fullname")"
      vl_pkg_status="$(pkg version -r "$vl_pkg_repo" -qUn "$vl_pkg_name" | awk '{print $2}')"

      case "$vl_pkg_status" in
        = )
          vl_pkg_status=OK
          ;;

        "<" )
          vl_pkg_status="NEED UPDATE"
          ;;

        ">" )
          vl_pkg_status="REPO VERSION LOWER"
          ;;

        "?" )
          vl_pkg_status="NO PACKAGE IN REPO"
          ;;

        "!" )
          vl_pkg_status="ERROR"
          log_err -s "${vl_pkg_name}: pkg can not compare version of package"
          ;;

        * )
          log_err -s "${vl_pkg_name}: unknown status ${vl_pkg_status}"
          vl_pkg_status="ERROR"
          ;;

      esac

      vl_status_file="${v_pkg_detail_status}/${vl_pkg_name}"
      pkg query 'installed=%t\nmainteiner=%m\nsize=%sb\nlocked=%k' "$vl_pkg_fullname" \
        > "${vl_status_file}"

      printf 'ver=%s\nrepo=%s\nstatus=%s\n' "${vl_pkg_ver}" "${vl_pkg_repo}" "${vl_pkg_status}" >> "$vl_status_file"
      pkg audit "$vl_pkg_fullname" \
        | awk '!($0 ~ "[0-9]* problem\\(s\\) in [0-9]* installed package\\(s\\) found") {print $0}' \
        > "${vl_status_file}.audit"

    done
}

pkg_check_up_status () {
  # Проверка статуса наличия обновления для пакета
  local vl_pkg_name
  local vl_pkg_repo

  cat /dev/null > "$v_pkg_update_status"
  pkg version -qUL = | awk '$2 != ">" {print $1}' | while read _pkg; do
      vl_pkg_name="$(pkg query '%n' "${_pkg}")"
      vl_pkg_repo="$(pkg query '%R' "${_pkg}")"
      log "Check update for ${vl_pkg_name} in ${vl_pkg_repo}"
      pkg version -Ur "${vl_pkg_repo}" -n "${vl_pkg_name}" \
      | awk '$2 != ">" && $2 != "=" {print $1}' \
      | tee -a "$v_pkg_update_status" \
      | awk '$0 != "" {print "UPDATE STATUS:", $0}' | log
  done

  pkg upgrade -Uqn | tee -a "$v_pkg_update_status" | awk '$0 != "" {print "PKG UPGRADE:", $0}' | log
}

pkg_do () {
  log_start "pkg_do"

  pkg_init

  pkg_check_up_status
  pkg audit -qF > "${v_pkg_update_status}.audit"

  pkg_make_detail

  log_end
}