#!/usr/bin/env bash

COMMIT_MSG_FILE="$1"
COMMIT_SOURCE="$2"

BOOTSTRAPDIR="bootstrap"
pkg_committed="$(cat "$(git rev-parse --show-toplevel)"/$BOOTSTRAPDIR/packages*.tsv | grep -v -e '^Name	Description	Source	Target' | cut -f1 | sort)"
pkg_onsystem=$(pacman -Qqett | grep -v "$(pacman -Qqg base-devel)" | sort)

# get files only in repo, and only on machine
only_committed=$(comm -23 <(echo "$pkg_committed") <(echo "$pkg_onsystem"))
only_onsystem=$(comm -13 <(echo "$pkg_committed") <(echo "$pkg_onsystem"))

# if we have no changes, do nothing
if [ -n "$only_onsystem" ] || [ -n "$only_committed" ]; then
    text=$(printf "\-- PACKAGE CHANGES --\nPackages on machine but not committed:\n%s\n\nPackages committed but not on machine:\n%s\n" "$only_onsystem" "$only_committed" | sed 's/^/# /gm')
else
    exit 0
fi

# prepend package changes to message
case $COMMIT_SOURCE in
"" | message, | template,)
    msg=$(echo "$text" | cat - "$COMMIT_MSG_FILE")
    printf "%s" "$msg" >"$COMMIT_MSG_FILE"
    ;;
esac