#!/usr/bin/env bash
set -euo pipefail

# Generate debian/changelog with a version derived from git. We build .debs
# for an internal apt repository only — never for Debian itself — so the
# changelog is generated at build time rather than hand-maintained, and the
# package uses the native source format (no separate upstream tarball).
#
# Versioning:
#   * A commit that is exactly a tag       -> the bare tag, e.g. v1.3.0 -> 1.3.0
#   * Any other commit                     -> <base>+git<date>.<hash>, e.g.
#     v1.2.0-4-g63ae7719caef               -> 1.2.0+git20260723.63ae7719caef
#
# The snapshot form uses the HEAD commit date (UTC) so versions increase
# monotonically over time: dpkg sorts 1.2.0 < 1.2.0+git<newer> < 1.3.0.
#
# Overridable via the environment:
#   DEB_DISTRIBUTION  target suite in the changelog (default: <codename>-tcl,
#                     the build image's Debian codename from /etc/os-release —
#                     e.g. trixie-tcl — so it tracks the image automatically)
#   DEB_MAINTAINER    changelog/maintainer trailer (default: Tiger Computing)

cd "$(dirname "$0")/.."

distribution="${DEB_DISTRIBUTION:-}"
if [ -z "$distribution" ] && [ -r /etc/os-release ]; then
	# shellcheck disable=SC1091
	codename="$(. /etc/os-release && printf '%s' "${VERSION_CODENAME:-}")"
	[ -n "$codename" ] && distribution="${codename}-tcl"
fi
# Fallback if the codename can't be determined (e.g. built off a non-Debian
# host); a real build always resolves it from the image above.
distribution="${distribution:-unstable}"

maintainer="${DEB_MAINTAINER:-Tiger Computing Ltd <hostmaster@tiger-computing.co.uk>}"

if tag=$(git describe --tags --exact-match HEAD 2>/dev/null); then
	version="${tag#v}"
else
	if base=$(git describe --tags --abbrev=0 2>/dev/null); then
		base="${base#v}"
	else
		# No tags reachable (e.g. a shallow clone without tags): fall back
		# to a fixed base rather than failing the build.
		base="0.0.0"
	fi

	commit_date=$(TZ=UTC0 git show -s --date=format-local:%Y%m%d --format=%cd HEAD)
	short_hash=$(git rev-parse --short=12 HEAD)
	version="${base}+git${commit_date}.${short_hash}"
fi

# Committer date in RFC 2822, so rebuilding the same commit is reproducible.
changelog_date=$(git show -s --format=%cD HEAD)
full_hash=$(git rev-parse HEAD)

cat > debian/changelog <<EOF
fleeting-plugin-proxmox (${version}) ${distribution}; urgency=medium

  * Automated build from git commit ${full_hash}.

 -- ${maintainer}  ${changelog_date}
EOF

echo "Generated debian/changelog for version ${version}" >&2
