#!/bin/bash
# Originally based on http://pastebin.com/raw.php?i=P5whH4Xh from sarnex on #d3d9 on freenode

#Usage: generate-d3d9-patch.sh
#	generate-d3d9-patch.sh <version>
# ie	generate-ded9-patch.sh 1.7.35

source ./common.sh

[ -z $LOGGED ] && exec > >(tee -a log)

# Variables
VERSION=$1
REPO_EXISTS=false
D3D9_REPO_DIR=wine-d3d9
D3D9_REPO_URI="git://github.com/ixit/wine.git"
WINE_REPO_URI="git://source.winehq.org/git/wine.git"

log "Checking if this is first run..."
if [ -d ${D3D9_REPO_DIR} ]; then
	log "Repo already exists"
	REPO_EXISTS=true;
fi

if ! $REPO_EXISTS; then
	log "Cloning D3D9 repository."
	git clone -q "${D3D9_REPO_URI}" "${D3D9_REPO_DIR}" || die "Initial clone of D3D9 failed"
fi

cd "${D3D9_REPO_DIR}"

if ! $REPO_EXISTS; then
	log "Adding WineHQ as 'upstream'"
	git remote add upstream "${WINE_REPO_URI}" > /dev/null || die "Failed to add upstream" #couldn't figure out how to use quiet flag
else
	log "Updating D3D9 repository"
	git fetch -q || die "Failed to fetch D3D9"
	git reset -q --hard origin
fi

log "Updating WineHQ repository."
git fetch -q upstream || non_fatal_die "Failed to fetch WineHQ"

TARGET="upstream/master"
if [ ! -z "${VERSION}" ]; then
	TARGET="wine-${VERSION}"
fi

log "Merging D3D9 and WineHQ histories"
git rebase -q ${TARGET} > /dev/null || die "Merge history failed"

log "Removing unnecessary patch content"
git diff ${TARGET} ./configure ./include/config.h.in | git apply -R
log "Generating the patch"
git diff ${TARGET} > ../wine-d3d9-latest.patch

log "Resetting repository state."
git reset -q --hard origin
git clean -f -d -q
