#!/bin/bash
#
# Armbian MOTD: Featured (news, apps and tips)
#

THIS_SCRIPT="tips"
MOTD_DISABLE=""

safe_source() { [[ -f "$1" ]] && . "$1"; }

safe_source /etc/default/armbian-motd
for f in ${MOTD_DISABLE}; do
  [[ "${f}" == "${THIS_SCRIPT}" ]] && exit 0
done

# --- helpers ---
_has_prev_output() {
  [[ -e /run/armbian-motd/.after_header.printed ]] \
  || [[ -e "${XDG_RUNTIME_DIR:-/tmp}/armbian-motd/.after_header.printed" ]]
}

# --- collect content ---

lines=()

# Featured feed (https://github.armbian.com/featured.json), cached daily by
# /etc/cron.daily/armbian-featured. Pick a random type first, so the many
# software entries don't crowd out news and the rest. Skip a stale cache.
featured="/var/lib/armbian/featured.json"
if [[ -n "$(find "$featured" -mtime -14 2>/dev/null)" ]] && command -v jq >/dev/null 2>&1; then
  mapfile -t tip < <(jq -r --arg today "$(date +%Y-%m-%d)" --argjson r1 "$RANDOM" --argjson r2 "$RANDOM" '
    [.entries[] | select((.expires // "") == "" or .expires >= $today) | select((.motd.line // "") != "")]
    | group_by(.type) | select(length > 0)
    | .[$r1 % length] | .[$r2 % length]
    | .motd.line, (.motd.hint // "")' "$featured" 2>/dev/null)
  [[ -n "${tip[0]}" ]] && lines+=("${tip[0]}")
  [[ -n "${tip[1]}" ]] && lines+=("${tip[1]}")
fi

# --- print (only if we actually have something to say) ---

if ((${#lines[@]})); then
  # One blank line ONLY if something printed earlier
  _has_prev_output && echo ""

  printf "\e[0;90m Featured:\x1B[0m\n\n"
  for l in "${lines[@]}"; do
    printf "%s\n" " $l"
  done
fi

exit 0
