#!/bin/bash
#
# Armbian MOTD: Tips (compact + robust)
#

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" ]]
}

# extract field from a tiny JSON object; prefer jq, fallback to sed
_json_get() {
  local key="$1" json="$2"
  if command -v jq >/dev/null 2>&1; then
    jq -r --arg k "$key" '.[$k] // empty' <<<"$json" 2>/dev/null
  else
    printf '%s\n' "$json" | sed -n -E "s/.*\"$key\":\"([^\"]*)\".*/\1/p"
  fi
}

# --- collect content ---

lines=()

# 1) Optional quote: /etc/update-motd.d/quotes.txt lines like: YYYY-MM-DD|Some text...
quotes="/etc/update-motd.d/quotes.txt"
if [[ -f "$quotes" ]]; then
  total=$(wc -l < "$quotes")
  if [[ "$total" -gt 0 ]]; then
    rline=$(( RANDOM % total + 1 ))
    raw=$(sed -n "${rline}p" "$quotes")
    due="${raw%%|*}"
    qtext="${raw#*|}"
    # show only if not expired or due is empty
    today=$(date +%Y-%m-%d)
    if [[ -z "$due" || "$today" < "$(date -d "$due" +%Y-%m-%d 2>/dev/null || echo 9999-12-31)" ]]; then
      [[ -n "$qtext" ]] && lines+=("$qtext")
    fi
  fi
fi

# 2) One non-expired recommend_message (if defined)
if [[ "$(declare -p recommend_messages 2>/dev/null)" == "declare -a"* ]]; then
  today=$(date +%Y-%m-%d)
  valid=()
  for item in "${recommend_messages[@]}"; do
    exp=$(_json_get expiration "$item")
    [[ -z "$exp" || "$today" < "$exp" ]] && valid+=("$item")
  done
  if ((${#valid[@]})); then
    pick=${valid[$RANDOM % ${#valid[@]}]}
    msg=$(_json_get message "$pick")
    url=$(_json_get url     "$pick")
    [[ -n "$msg" ]] && lines+=("$msg")
    [[ -n "$url" ]] && lines+=("$url")
  fi
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 Tips:\x1B[0m\n\n"
  for l in "${lines[@]}"; do
    printf "%s\n" " $l"
  done
fi

exit 0
