#!/bin/bash

# Bash options:
set -eu

# ====== Get package configuration ==========================================
CHANGELOG_HEADER="`head -n1 debian/changelog`"

# The package name, e.g. MyApplication
PACKAGE=`echo ${CHANGELOG_HEADER} | sed -e "s/(.*//" -e "s/ //g"`
# The package distribution, e.g. precise, raring, ...
PACKAGE_DISTRIBUTION=`echo ${CHANGELOG_HEADER} | sed -e "s/[^)]*)//" -e "s/;.*//g" -e "s/ //g"`
# The package's version, e.g. 1.2.3-1ubuntu1
PACKAGE_VERSION=`echo ${CHANGELOG_HEADER} | sed -e "s/.*(//" -e "s/).*//" -e "s/ //g" -e "s/ //g" -e "s/^[0-9]://g"`
# The package's output version, e.g. 1.2.3-1ubuntu
OUTPUT_VERSION=`echo ${PACKAGE_VERSION}   | sed -e "s/\(ubuntu\|ppa\)[0-9]*$/\1/"`
# The package's Debian version, e.g. 1.2.3-1
DEBIAN_VERSION=`echo ${OUTPUT_VERSION}    | sed -e "s/\(ubuntu\|ppa\)$//1"`
# The package's upstream version, e.g. 1.2.3
UPSTREAM_VERSION=`echo ${DEBIAN_VERSION}  | sed -e "s/-[0-9]*$//"`

TARBALL="${PACKAGE}-${UPSTREAM_VERSION}.tar.xz"
if [ ! -e "${TARBALL}" ] ; then
   echo >&2 "ERROR: No source tarball ${TARBALL} found!"
   exit 1
fi

# ====== Check contents =====================================================
gitFile="$(mktemp)"
tarballFile="$(mktemp)"
trap 'rm -rf "${gitFile}" "${tarballFile}"' EXIT

git ls-files         | sort >"${gitFile}"
tar tJf "${TARBALL}" | sed -e 's#[^/]*/##' -e '/\/$/d' | sort >"${tarballFile}"

echo "----- Files tracked by Git but not in tarball: ------"
join "${gitFile}" "${tarballFile}" -v 1
echo "----- Files in tarball but not tracked by Git: ------"
results="$(join "${tarballFile}" "${gitFile}" -v 1)"
if [ "${results}" != "" ] ; then
   echo "${results}"
fi
echo "-----------------------------------------------------"

if [ "${results}" != "" ] ; then
   echo "ERROR: There are untracked filed in the tarball!"
   exit 1
fi
