#!/bin/bash

# Examples of using:
# ./libsnl_get-orig-source.sh
# main ideas of this script was taken from elmerfem 

PACKAGE=libsnl
SVN_REPO="http://svn.code.sf.net/p/libsnl/code/trunk"

SVN_REVISION=$(svn log "${SVN_REPO}" | head -n2 |grep "r[0-9]\+" | sed -e "s/^r\([0-9]\+\).*$/\1/")
if [ -z "${SVN_REVISION}" ]; then
    echo "Failed to find last SVN revision."
    exit 1
fi

echo "SVN_REVISION = ${SVN_REVISION}"

CUR_MAJ_VERSION=$(curl "${SVN_REPO}/src/snlVersion.h" 2>&1 | grep "#define SNL_VERSION_MAJOR" | sed -e "s/^#define SNL_VERSION_MAJOR \(.\+\)\r$/\1/")
CUR_MIN_VERSION=$(curl "${SVN_REPO}/src/snlVersion.h" 2>&1 | grep "#define SNL_VERSION_MINOR" | sed -e "s/^#define SNL_VERSION_MINOR \(.\+\)\r$/\1/")
CUR_REL_VERSION=$(curl "${SVN_REPO}/src/snlVersion.h" 2>&1 | grep "#define SNL_VERSION_RELEASE" | sed -e "s/^#define SNL_VERSION_RELEASE \(.\+\)\r$/\1/")

CUR_VERSION="${CUR_MAJ_VERSION}.${CUR_MIN_VERSION}.${CUR_REL_VERSION}"
if [ -z "${CUR_VERSION}" ]; then
    echo "Failed to define current version."
    exit 1
fi
    
echo "CUR_VERSION = ${CUR_VERSION}"

SRC_VERSION="${CUR_VERSION}.svn.${SVN_REVISION}"
echo "SRC_VERSION  = ${SRC_VERSION}"

TARBALL="${PACKAGE}_${SRC_VERSION}.orig.tar.xz"
rm -rf "${PACKAGE}-${SRC_VERSION}" "${TARBALL}"

echo "Start svn export, this will take some time..."
svn export -r ${SVN_REVISION} "${SVN_REPO}" "${PACKAGE}-${SRC_VERSION}" > svn-export.log || exit 1
echo "svn export finished successfully."

tar -cJf ${TARBALL} "${PACKAGE}-${SRC_VERSION}" || exit 1
rm -rf "${PACKAGE}-${SRC_VERSION}" svn-export.log

echo "${TARBALL} was created."
