#!/bin/bash
#
# Purpose: Check for available version updates in binaries.conf and compile.conf,
#          and that everything in packages.conf can still be installed
#          (a tool for HamPack maintainers; it changes nothing)
#
# Usage:   hampackcheck [versions|packages]   (both, if neither is given)
#          Exits 1 if a package or Flatpak can't be found, or couldn't be checked.

source "$(dirname "$(realpath "$0")")/lib.sh"

BINARIES_CONF="${HAMPACK_BINARIES_CONF:-$HAMPACK_DIR/binaries.conf}"
COMPILE_CONF="${HAMPACK_COMPILE_CONF:-$HAMPACK_DIR/compile.conf}"
PACKAGES_CONF="${HAMPACK_PACKAGES_CONF:-$HAMPACK_DIR/packages.conf}"
AUR_RPC="https://aur.archlinux.org/rpc/v5/info"
FLATHUB_API="https://flathub.org/api/v2/appstream"

# Fetch latest release tag via GitHub API, stripping leading "v"
github_latest() {
  curl -sf "https://api.github.com/repos/$1/releases/latest" \
    | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' \
    | sed 's/^v//'
}

# Latest release tag in a git repo, stripping leading "v". Only plain version
# tags count (1.2.3 or v1.2.3), not pre-releases like 1.8-beta1.
git_latest_tag() {
  git ls-remote --tags --refs "$1" 2> /dev/null \
    | sed 's|.*refs/tags/||' \
    | grep -E '^v?[0-9]+(\.[0-9]+)+$' \
    | sed 's/^v//' \
    | sort -V \
    | tail -n1
}

# Latest commit on a GitHub repo's default branch
github_head() {
  git ls-remote "https://github.com/$1" HEAD 2> /dev/null | cut -f1
}

print_result() {
  local app="$1" pinned="$2" latest="$3" manual_url="$4" source="${5:-GitHub API}"

  if [ -n "$manual_url" ]; then
    printf "  %-20s pinned=%-15s  (manual check: %s)\n" "$app" "${pinned:0:15}" "${manual_url%/*}"
  elif [ -z "$latest" ]; then
    printf "  %-20s pinned=%-15s  (%s unavailable)\n" "$app" "${pinned:0:15}" "$source"
  elif [ "$pinned" = "$latest" ]; then
    printf "  %-20s up to date (%s)\n" "$app" "${pinned:0:15}"
  else
    printf "  %-20s pinned=%-15s  latest=%-15s  ** UPDATE AVAILABLE **\n" "$app" "${pinned:0:15}" "${latest:0:15}"
  fi
}

# parse_conf callback for binaries.conf
check_binary() {
  local app="${CONF[_name]}" version="${CONF[version]}" url="${CONF[url]}"
  [ -n "$version" ] || return 0
  [ -n "${CONF[sha256]}" ] || echo "  $app has no sha256=, so its download isn't verified"

  if [[ "$url" =~ ^https://raw\.githubusercontent\.com/([^/]+/[^/]+)/ ]]; then
    print_result "$app" "$version" "$(github_head "${BASH_REMATCH[1]}")" "" "git"
  elif [[ "$url" =~ github\.com/([^/]+)/([^/]+) ]]; then
    print_result "$app" "$version" "$(github_latest "${BASH_REMATCH[1]}/${BASH_REMATCH[2]%.git}")" ""
  else
    print_result "$app" "$version" "" "$url"
  fi
}

# Date (YYYY-MM-DD, UTC) a URL was last modified, from its Last-Modified header
last_modified_date() {
  local header
  header="$(curl -sfIL "$1" | sed -n 's/^[Ll]ast-[Mm]odified: *//p' | tail -n1 | tr -d '\r')"
  [ -n "$header" ] && date -u -d "$header" +%F
}

# parse_conf callback for compile.conf. git= apps are built from the tag
# matching their version, so compare against the repo's tags, not releases.
# Repos without version tags are compared by their pinned ref= against HEAD,
# and archives versioned by date by their Last-Modified date.
check_compiled() {
  local app="${CONF[name]:-${CONF[_name]}}" version="${CONF[version]}" ref="${CONF[ref]}"
  [ -n "$version" ] || return 0

  if [ -n "${CONF[git]}" ]; then
    local latest
    latest="$(git_latest_tag "${CONF[git]}")"
    if [ -z "$latest" ] && [ -n "$ref" ]; then
      local head
      head="$(git ls-remote "${CONF[git]}" HEAD 2> /dev/null | cut -f1)"
      if [ "$head" = "$ref" ]; then
        print_result "$app" "$version" "$version" ""
      else
        print_result "$app" "$version" "${head:+HEAD ${head:0:10}}" "" "git HEAD"
      fi
    else
      print_result "$app" "$version" "$latest" "" "version tags"
    fi
  elif [[ "$version" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
    print_result "$app" "$version" "$(last_modified_date "${CONF[wget]}")" "" "Last-Modified"
  else
    print_result "$app" "$version" "" "${CONF[wget]}"
  fi
}

# Check that each package in packages.conf is in pacman's sync databases (as
# a package or a group) or on the AUR, and each Flatpak is on Flathub. Repo
# packages are looked up locally, so run `pacman -Sy` first for fresh results.
# A name that's only provided by another package still installs, but is
# reported so packages.conf can use the real name.
# Returns 1 if anything is missing or couldn't be checked.
check_packages() {
  local packages flatpak_ids p provider not_in_repos=() aur_names code status=0
  # grep drops the blank line printf makes of an empty list
  mapfile -t packages < <(source "$PACKAGES_CONF"; printf '%s\n' "${UTILITIES[@]}" "${APPLICATIONS[@]}" | grep .)
  mapfile -t flatpak_ids < <(source "$PACKAGES_CONF"; printf '%s\n' "${FLATPAKS[@]}" | grep .)

  for p in "${packages[@]}"; do
    if pacman -Si "$p" > /dev/null 2>&1 || pacman -Sg "$p" > /dev/null 2>&1; then
      continue
    elif provider="$(pacman -Sddp --print-format %n "$p" 2> /dev/null)" && [ -n "$provider" ]; then
      echo "  $p is provided by $provider; packages.conf could name that instead"
    else
      not_in_repos+=("$p")
    fi
  done
  echo "  ${#packages[@]} packages, $(( ${#packages[@]} - ${#not_in_repos[@]} )) in the repos"

  if (( ${#not_in_repos[@]} > 0 )); then
    local args=()
    for p in "${not_in_repos[@]}"; do args+=(--data-urlencode "arg[]=$p"); done
    if ! aur_names="$(set -o pipefail; curl -sfG "$AUR_RPC" "${args[@]}" | jq -r '.results[].Name')"; then
      echo "  The AUR couldn't be reached, so these weren't checked: ${not_in_repos[*]}"
      return 1
    fi
    for p in "${not_in_repos[@]}"; do
      if grep -qxF "$p" <<< "$aur_names"; then
        echo "  $p is on the AUR"
      else
        echo "  $p is in neither the repos nor the AUR  ** MISSING **"
        status=1
      fi
    done
  fi

  for p in "${flatpak_ids[@]}"; do
    code="$(curl -s -o /dev/null -w '%{http_code}' "$FLATHUB_API/$p")"
    case "$code" in
      200) echo "  $p is on Flathub" ;;
      404) echo "  $p is not on Flathub  ** MISSING **"; status=1 ;;
      *)   echo "  $p couldn't be checked: Flathub answered ${code:-nothing}"; status=1 ;;
    esac
  done

  return $status
}

# --- Main ---

what="${1:-all}"
case "$what" in
  all|versions|packages) ;;
  *) echo "Usage: $(basename "$0") [versions|packages]"; exit 2 ;;
esac

if [ "$what" != packages ]; then
  for conf in "$BINARIES_CONF" "$COMPILE_CONF"; do
    if [ ! -f "$conf" ]; then
      echo "Error: $conf not found."
      exit 1
    fi
  done

  echo "Checking HamPack application versions..."
  echo "=== binaries.conf ==="
  parse_conf "$BINARIES_CONF" check_binary
  echo ""
  echo "=== compile.conf ==="
  parse_conf "$COMPILE_CONF" check_compiled
fi

if [ "$what" != versions ]; then
  if [ ! -f "$PACKAGES_CONF" ]; then
    echo "Error: $PACKAGES_CONF not found."
    exit 1
  fi
  [ "$what" = packages ] || echo ""
  echo "=== packages.conf ==="
  check_packages || exit 1
fi
