#!/bin/bash
#
# Purpose : Show which version of MiniServer this machine is running
#
# MiniServer is a rolling release, so its version is the date of the commit
# the local checkout is on, plus the short hash to tell same-day commits apart,
# e.g. 2026.10.22 (c5f0651). The kernel is shown separately because it comes
# from Arch, not MiniServer.
#
# version --check prints the newer version and exits 0 if one is available,
# exits 1 if this machine is up to date, or 2 if it couldn't check.

MINISERVER="$HOME/.local/share/MiniServer"

source "$MINISERVER/utils.sh"

if ! git -C "$MINISERVER" rev-parse --git-dir &> /dev/null; then
  echo "MiniServer isn't installed in $MINISERVER."
  exit 2
fi

# Version string for a commit, e.g. 2026.10.22 (c5f0651)
describe() {
  git -C "$MINISERVER" log -1 --format='%cd (%h)' --date=format:%Y.%m.%d "$1"
}

# Print the newer version if the remote has commits this checkout doesn't.
# Returns 1 if up to date, 2 if the remote couldn't be reached.
newer_version() {
  GIT_TERMINAL_PROMPT=0 timeout 30 git -C "$MINISERVER" fetch --quiet &> /dev/null || return 2
  local behind
  behind="$(git -C "$MINISERVER" rev-list --count 'HEAD..@{upstream}' 2> /dev/null)" || return 2
  (( behind > 0 )) || return 1
  describe '@{upstream}'
}

if [ "$1" = "--check" ]; then
  newer_version
  exit
fi

version="$(describe HEAD)"

# Local edits to the checkout mean this isn't exactly the version above
if [ -n "$(git -C "$MINISERVER" status --porcelain --untracked-files=no)" ]; then
  version="$version, modified"
fi

if latest="$(newer_version)"; then
  version="$version, $latest is available (run update)"
fi

kernel="$(uname -r)"
# If the running kernel's modules are gone, a newer kernel was installed
if [ ! -d "/usr/lib/modules/$kernel" ]; then
  kernel="$kernel (newer kernel installed, reboot to use it)"
fi

# 10-pacman.sh rewrites this log on every update
if [ -f "$PACMAN_UPDATE_LOG" ]; then
  last_update="$(date -r "$PACMAN_UPDATE_LOG" '+%Y-%m-%d %H:%M')"
else
  last_update="never"
fi

echo "MiniServer  $version"
echo "Kernel       $kernel"
echo "Last update  $last_update"
