#!/usr/bin/env bash
if [[ ${BASH_SOURCE} = */* ]]; then
	SCRIPT_DIR=${BASH_SOURCE%/*}/
else
	SCRIPT_DIR=./
fi

. ${SCRIPT_DIR}/generate-docs.bashlib || { echo "Failed to source generate-docs.bashlib!" ; exit 1 ; }

export ABI_X86="64" # we don't want to build multiple variants & easier to glob below
export FVWM3_DOCS_PREBUILT=0

set_source_date_epoch_from_tag() {
	local ebuild_ref=${1}
	local tag
	local tmp_repo
	local tag_epoch

	if ! atomset "${ebuild_ref}" >/dev/null 2>&1 ; then
		ewarn "Unable to parse ebuild reference '${ebuild_ref}' for tag lookup"
		return 1
	fi

	tag=${PV}
	tmp_repo=$(mktemp -d) || return 1

	if git -C "${tmp_repo}" init -q \
		&& git -C "${tmp_repo}" remote add origin "https://github.com/fvwmorg/fvwm3.git" \
		&& git -C "${tmp_repo}" fetch -q --depth 1 origin "refs/tags/${tag}:refs/tags/${tag}" ; then
		tag_epoch=$(git -C "${tmp_repo}" log -1 --format=%ct "refs/tags/${tag}" 2>/dev/null)
	fi

	rm -rf "${tmp_repo}"

	if [[ -z ${tag_epoch} ]] ; then
		ewarn "Failed to resolve GitHub tag date for fvwm3 tag '${tag}'"
		return 1
	fi

	export SOURCE_DATE_EPOCH="${tag_epoch}"
	einfo "Using SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH} from fvwm3 tag '${tag}'"
}

set_source_date_epoch_from_tag "$1" || exit 1

generate-docs_copy_docs() {
	ebegin "Copying man pages to ${dir}/${P}-docs"
	cp -ra "${WORKDIR}"/../image/usr/share/man "${dir}"/${P}-docs/
	ebegin "Copying htmldoc to ${dir}/${P}-docs"
	cp -ra "${WORKDIR}"/../image/usr/share/doc/${PF}/html "${dir}"/${P}-docs/
	eend $? || exit 1
}

generate-docs $@
