#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later

# When provided with a git repo, which has been used to produce a
# distribution tar.gz (with make dist) and the resultant tar-file,
# lists files which appear in one or the other only, to help check
# for missing EXTRA_DIST entries in Makefile.am files.

# Note: this list uses shell globbing, i.e. an * matches any number of
# subdirectories, so it is somewhat different to e.g. .gitignore
ignore=$(tr '\n' '|' <<'END'
autom4te.cache/*
CMakeLists.txt
config.h
config.log
config.status
.git/*
.githooks/*
Makefile
*/Makefile
makeself/README.md
netdata-*.tar.*
packaging/*
src/.deps/*
stamp-h1
tests/profile/*
.travis.yml
END
)

scriptname=tar-compare
if ! MYTMP=$(mktemp -d -t $scriptname-XXXXXX)
then
            echo >&2
            echo >&2
            echo >&2 "Cannot create temporary directory."
            echo >&2
            exit 1
fi

cleanup() {
  status=$?
  rm -rf "${MYTMP}"
  exit $status
}

# clean up if we get stopped by Crtl-C or forced logout or normal exit
trap cleanup INT
trap cleanup HUP
trap cleanup 0

if [ $# -ne 2 ]
then
  echo "Usage: tar-compare git-dir tar-gz-file"
  exit 1
fi

mkdir $MYTMP/unpack
tar xfzC "$2" $MYTMP/unpack || exit
(cd "$1" && find . -type f | sort > $MYTMP/git-list)
(cd "$MYTMP/unpack"/* && find . -type f | sort > $MYTMP/tar-list)

comm -23 $MYTMP/git-list $MYTMP/tar-list | cut -f2- -d'/' > $MYTMP/only-in-git

while read name
do
  eval "case $name in $ignore,) : ;; *) echo 'In git but not tar: $name' >> '$MYTMP/out' ;; esac"
done < $MYTMP/only-in-git

if [ -s $MYTMP/out ]
then
  cat $MYTMP/out
  echo "Release tarfile differs from git content unexpectedly."
  echo "Ensure all files are packaged, or ignored by packaging/tar-compare"
  exit 1
fi
exit 0
