#!/bin/bash

# FIXME: This is broken.

# 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

PKGLIST_CUR_MD5="$(md5sum /etc/pkglist 2>/dev/null)"
TEMPLATE_CUR_MD5="$(md5sum /etc/slackpkg/templates/$(hostname --short).template 2>/dev/null)"

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

cd /etc || exot 1
git rev-parse --show-toplevel >/dev/null 2>&1 && {
  [[ -z "$PKGLIST_CUR_MD5" ]] && [[ -e pkglist ]] && {
    git add pkglist >/dev/null || exit 1
  }
  [[ -z "$TEMPLATE_CUR_MD5" ]] && [[ -e "slackpkg/templates/$(hostname --short).template" ]] && {
    git add "slackpkg/templates/$(hostname --short).template" >/dev/null || exit 1
  }
  { [[ -e pkglist ]] && [[ "$(md5sum pkglist 2>/dev/null)" != "$PKGLIST_CUR_MD5" ]]; } || \
      { [[ -e "slackpkg/templates/$(hostname --short).template" ]] && \
      [[ "$(md5sum "slackpkg/templates/$(hostname --short).template" 2>/dev/null)" != "$TEMPLATE_CUR_MD5" ]]; } && {
    git commit -m "Update pkglist (and/or." pkglist >/dev/null || exit 1
  }
}

exit 0
