#!/bin/bash
# Update the /etc/pkglist file, the record of installed packages on the system.

# Check for an /etc/os-release.
[[ ! -e /etc/os-release ]] && {
  printf "%s: %s\\n" "${BASH_SOURCE[0]}" "No /etc/os-release to determine system." >&2
  exit 1
}

# Source system info.
# shellcheck disable=SC1091
. /etc/os-release

# Create package list depending on system type.
case "$ID" in
  'alpine')
    apk list -I | cut -d' ' -f1 | rev | cut -d- -f3- | rev >/etc/pkglist
    ;;
  'debian'|'devuan'|'ubuntu')
    dpkg-query --show --showformat='${Package}\n' >/etc/pkglist
    ;;
  'slackware')
    slackpkg -batch=on -default_answer=y generate-template "$(hostname --short)" >/dev/null
    [[ -L /etc/pkglist ]] && rm -f /etc/pkglist
    printf "%s\\n" /var/log/packages/* | rev | cut -d- -f4- | rev >/etc/pkglist
    ;;
  'void')
    xbps-query -l | awk '{ print $2 }' | rev | cut -d- -f2- | rev >/etc/pkglist
    ;;
  *)
    printf "%s: %s\\n" "${BASH_SOURCE[0]}" "Unsupported system." >&2
    exit 1
    ;;
esac

exit 0
