autoconf: Automatically derive version number from latest git tag

with a fallback to get the version string from a .tarball-version file
diff --git a/Makefile.am b/Makefile.am
index 4ef0813..b11de57 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -4,7 +4,11 @@
 
 EXTRA_DIST = \
 	docs \
-	README.md
+	README.md \
+	git-version-gen
+
+dist-hook:
+	echo $(VERSION) > $(distdir)/.tarball-version
 
 docs/html: $(top_builddir)/doxygen.cfg $(top_srcdir)/src/*.c $(top_srcdir)/src/*.h $(top_srcdir)/include/libimobiledevice/*.h
 	rm -rf docs/html
diff --git a/configure.ac b/configure.ac
index 8fb032d..503051f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2,7 +2,7 @@
 # Process this file with autoconf to produce a configure script.
 
 AC_PREREQ([2.68])
-AC_INIT([libimobiledevice], [1.3.1], [https://github.com/libimobiledevice/libimobiledevice/issues], [], [https://libimobiledevice.org])
+AC_INIT([libimobiledevice], [m4_esyscmd(./git-version-gen $RELEASE_VERSION)], [https://github.com/libimobiledevice/libimobiledevice/issues], [], [https://libimobiledevice.org])
 AM_INIT_AUTOMAKE([dist-bzip2 no-dist-gzip check-news])
 m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES])
 AC_CONFIG_SRCDIR([src/])
@@ -17,12 +17,18 @@
 # CURRENT : REVISION : AGE
 LIBIMOBILEDEVICE_SO_VERSION=6:0:0
 
+AC_SUBST(LIBIMOBILEDEVICE_SO_VERSION)
+
+# Check if we have a version defined
+if test -z $PACKAGE_VERSION; then
+  AC_MSG_ERROR([PACKAGE_VERSION is not defined. Make sure to configure a source tree checked out from git or that .tarball-version is present.])
+fi
+
 dnl Minimum package versions
 LIBUSBMUXD_VERSION=2.0.2
 LIBPLIST_VERSION=2.2.0
 LIMD_GLUE_VERSION=1.0.0
 
-AC_SUBST(LIBIMOBILEDEVICE_SO_VERSION)
 AC_SUBST(LIBUSBMUXD_VERSION)
 AC_SUBST(LIBPLIST_VERSION)
 AC_SUBST(LIMD_GLUE_VERSION)
diff --git a/git-version-gen b/git-version-gen
new file mode 100755
index 0000000..3eb6a42
--- /dev/null
+++ b/git-version-gen
@@ -0,0 +1,19 @@
+#!/bin/sh
+SRCDIR=`dirname $0`
+if test -n "$1"; then
+  VER=$1
+else
+  if test -d "${SRCDIR}/.git" && test -x "`which git`" ; then
+    git update-index -q --refresh
+    if ! VER=`git describe --tags --dirty 2>/dev/null`; then
+      COMMIT=`git rev-parse --short HEAD`
+      DIRTY=`git diff --quiet HEAD || echo "-dirty"`
+      VER=`sed -n '1,/RE/s/Version \(.*\)/\1/p' ${SRCDIR}/NEWS`-git-${COMMIT}${DIRTY}
+    fi
+  else
+    if test -f "${SRCDIR}/.tarball-version"; then
+      VER=`cat "${SRCDIR}/.tarball-version"`
+    fi
+  fi
+fi
+printf %s "$VER"