#!/bin/bash

. /etc/init.d/functions.sh

VER="$1"
PVER="$2"

DIR="$(pwd)"
GIT_URL="${GIT_URL:-"git://xenbits.xen.org/xen.git"}"
GIT_BRANCH="${GIT_BRANCH:-stable-${VER:0:3}}"
PATCHDIR="tmp/patches-upstream"
INFODIR="${PATCHDIR}/info"
GIT="$(which git)"

ARCHIVE="xen-${VER}-upstream-patches-${PVER}.tar.xz"
OMITFILE=${3:-"${DIR}/xen-${VER}.omit"}
TAKEFILE=${4:-"${DIR}/xen-${VER}.take"}
EXTRA_DIR="${DIR}/extra-${VER}"

if [[ $# -lt 2 ]]; then
	einfo "Usage: $0 <pkg ver> <patch ver> [omitted file]"
	exit 1
fi

if [[ -z ${GIT} ]]; then
	eerror "git not found!"
	exit 1
fi

if [[ -e ${ARCHIVE} ]]; then
	eerror "Archive '${ARCHIVE}' does already exist! Abort."
	exit 1
fi

rm -rf tmp
rm -f ${ARCHIVE}

mkdir -p ${INFODIR}

pushd ${PATCHDIR} >/dev/null || exit 1
${GIT} clone -b ${GIT_BRANCH} ${GIT_URL} || exit 1
pushd xen >/dev/null || exit 1
${GIT} format-patch $(git rev-parse RELEASE-$1)..$(git rev-parse origin/${GIT_BRANCH}) -o ../. || exit 1
popd >/dev/null|| exit 1

for PATCH in *.patch; do
	SUFFIX=""
	if [[ -f ${TAKEFILE} ]] && $(grep -q ${PATCH:5} ${TAKEFILE}); then
		continue
	fi
	if [[ -f ${OMITFILE} ]] && $(grep -q ${PATCH:5} ${OMITFILE}); then
		ewarn "patch omitted: ${PATCH}"
		SUFFIX=".omitted"
		mv ${PATCH} ${PATCH/-xen-[0-9].[0-9].[0-9]-/_all_}${SUFFIX} || exit 1
	fi
done

# copy extra patches, also provided by upstream but not belong to xen repo
if [[ -d ${EXTRA_DIR} ]]; then
	cp -rf ${EXTRA_DIR}/* . || exit 1
fi

rm -rf xen || exit 1
popd >/dev/null || exit 1

if [[ -e ../README.Gentoo.patches ]]; then
	cp ../README.Gentoo.patches ${INFODIR}/ || exit 1
else
	if [[ -e README.Gentoo.patches ]]; then
		cp README.Gentoo.patches ${INFODIR}/ || exit 1
	fi
fi
if [[ -f ${TAKEFILE} ]]; then
	cp ${TAKEFILE} ${INFODIR}/ || exit 1
fi

if [[ -f ${OMITFILE} ]]; then
	cp ${OMITFILE} ${INFODIR}/ || exit 1
fi

cat >${INFODIR}/README <<-EOF
	Patchset generated on $(date).

	This patchset was automatically generated using upstream's git tree
	located at ${GIT_URL}.
	Refer to ${TAKEFILE} if patches are marked to be applied, also Gentoo bug id.
	Refer to ${OMITFILE} if patches are marked to be omitted.
EOF

cp $0 ${INFODIR}/ || exit 1

tar -cJf ${ARCHIVE} -C tmp . || exit 1
rm -rf tmp

einfo "Patchset generation run successfully :)"
einfo "File size of ${ARCHIVE}: $(du -bh ${ARCHIVE} | cut -f1)"
