#!/bin/sh -e
# Copyright: 2013-2015 Michael Gilbert <mgilbert@debian.org>
# License: LGPL-2.1+

# check for version argument
if [ "$#" -lt "1" ]; then
  echo "usage: $(basename $0) <upstream version number>"
  exit 1
fi

# terminate if we're not building from a git tree
if [ ! -d ".git" ]; then
  echo "error: importing only supported for git checkouts"
  exit 1
fi

# ignore changes to files that will be automatically generated
git update-index --assume-unchanged configure include/config.h.in

# pull specified tag from upstream repository
version="$1"
debian="https://anonscm.debian.org/git/pkg-wine/wine.git"
debian_branch="$(git rev-parse --abbrev-ref HEAD)"
upstream_branch="upstream-stable"
winehq="git://source.winehq.org/git/wine.git"
tag="wine-$version"
git checkout ${upstream_branch}
git pull $debian ${upstream_branch}
git pull --no-edit $winehq tag "$tag" || echo "unable to fetch tag $tag"

# merge upstream into our branch (favoring "their" changes)
git checkout ${debian_branch}
git merge --strategy-option=theirs ${upstream_branch}

# format the "New upstream release" message
tag_time=`git cat-file tag "$tag" | sed -n 's/tagger .*<.*> \([0-9]*\) .*/\1/p'`
release_date=`LC_ALL=C date -u -d "@$tag_time" +"%b %-d, %Y"`

# create the initial changelog entry
dch -v "$(echo $version|sed "s/-/~/")-1" "New upstream release $version, released $release_date."
sed -n 's/^  - \(.*\)/- \1/p' ANNOUNCE | while read line; do
  dch $line
done

# set upstream's SERVER_PROTOCOL_VERSION in request.patch
# this is usually stored in include/wine/server_protocol.h, but we clean that file because it is generated
proto_version=$(expr $(grep "#define SERVER_PROTOCOL_VERSION" include/wine/server_protocol.h | cut -d\  -f 3) - 1)
[ "$proto_version" -lt 32767 ] || {
    echo "error: proto_version $proto_version is not valid."
    exit 1;}
sed -i "s|\(+    my \$protocol = \)[[:digit:]]*;|\1${proto_version};|" debian/patches/generate/request.patch
