#!/bin/sh

# Script used to generate the orig source tarball for x264.

X264_GIT_URL="https://code.videolan.org/videolan/x264.git"
X264_GIT_COMMIT="baee400fa9ced6f5481a728138fed6e867b0ff7f"
DATE_RETRIEVED="20220602"
COMMIT_SHORT_FORM="$(echo $X264_GIT_COMMIT | \
                     sed -e 's/^\([[:xdigit:]]\{,7\}\).*/\1/')"

git clone "$X264_GIT_URL" "x264-git${COMMIT_SHORT_FORM}"
cd "x264-git${COMMIT_SHORT_FORM}"
git checkout "$X264_GIT_COMMIT"

# We must determine the version after switching to the right commit and before
# making any modifications
POINTVER=$(./version.sh | grep X264_POINTVER | \
  sed -e 's/.*"\([.0-9]\+\)[[:space:]]\+\([a-fA-F0-9]\+\)".*/\1 \2/' | \
  cut -d ' ' -f 1)
X264_VERSION="${POINTVER}+git${COMMIT_SHORT_FORM}"

# Rewrite version.sh since .git repo won't be available in Debian packaging.
LINE1=$(./version.sh | grep X264_VERSION)
LINE2=$(./version.sh | grep X264_POINTVER)
cat <<EOF >version.sh
#!/bin/sh
# Script modified from upstream source for Debian packaging since packaging
# won't include .git repository.
echo '${LINE1}'
echo '${LINE2}'
EOF
chmod a+x version.sh

cp -vf /usr/share/misc/config.guess .
cp -vf /usr/share/misc/config.sub .
cd ..

# Rename the upstream directory
mv "x264-git${COMMIT_SHORT_FORM}" "x264-${X264_VERSION}"

# Remove temp files and other cruft from source tarball
# The find command snippet here was taken from debhelper's dh_clean command
# with some modification to delete more unneeded files.
echo "Removing temp files and other cruft from source tarball"
find x264-${X264_VERSION} \( \( -type f -a \
  \( -name '#*#' -o -name '.*~' -o -name '*~' -o -name DEADJOE \
  -o -name '*.orig' -o -name '*.rej' -o -name '*.bak' \
  -o -name '.*.orig' -o -name .*.rej -o -name '.SUMS' \
  -o -name TAGS -o \( -path '*/.deps/*' -a -name '*.P' \) \
  -o -name config.status -o -name config.cache -o -name config.log \
  \) -exec rm -f "{}" \; \) -o \
  \( -type d -a -name autom4te.cache -prune -exec rm -rf "{}" \; \) \)
rm -rf x264-${X264_VERSION}/.git
rm -f x264-${X264_VERSION}/.gitignore

# Remove empty directories
echo "Removing empty directories"
find x264-${X264_VERSION} -type d -empty -delete

tar --exclude-vcs -czf "x264_${X264_VERSION}.orig.tar.gz" \
  "x264-${X264_VERSION}/"
