#!/bin/sh
set -o nounset
set -o errexit

DIST_GIT="$(cd "$(dirname "$0")"; pwd)"
SPEC="${DIST_GIT}/snakemake.spec"

WORKDIR="$(mktemp -d)"
trap "rm -rf '${WORKDIR}'" INT TERM EXIT
cd "${WORKDIR}"
# Make sure we have an absolute path to the working directory.
WORKDIR="${PWD}"

echo "==== Download source archive ====" 1>&2
SOURCE0="$(
  spectool --list-files "${SPEC}" |
    awk '$1 == "Source0:" { print $2 }'
)"
TARNAME="$(basename "${SOURCE0}")"
XDIR="$(basename "${TARNAME}" '.tar.gz')"
spectool --get-files "${SPEC}"

echo "==== Extract source archive ====" 1>&2
tar -xzf "${TARNAME}"
# Capture modification time from the original source archive, before we touch
# anything; everything in our asset archive will have this mtime for better
# reproducibility.
MTIME="$(stat --format='%Y' "${XDIR}/src/snakemake/assets/")"

echo "==== Apply patches ====" 1>&2
spectool --list-files "${SPEC}" |
  awk '/^Patch/ && !/modified-assets/ { print $2 }' |
  while read -r patchfile
  do
    set -o nounset
    set -o errexit
    echo "--> ${patchfile}" 1>&2
    cd "${WORKDIR}/${XDIR}"
    patch -p1 < "${DIST_GIT}/$(basename "${patchfile}")"
  done

echo "==== Download assets ====" 1>&2
PYTHONPATH="${PWD}/${XDIR}/src/snakemake" python3 <<'EOF'
from assets import Assets
Assets.deploy()
EOF

echo "==== Modify assets ====" 1>&2
echo "--> Remove array-flat-polyfill (CC0-1.0 code, unused)" 1>&2
target='src/snakemake/assets/data/vega-lite/vega-lite.js'
echo "To be removed from ${target}:" 1>&2
grep -E '^[[:blank:]]*Array\.prototype\.flat[[:blank:]]*\|\|' \
    "${XDIR}/${target}" 1>&2
sed -r -i '/^[[:blank:]]*Array\.prototype\.flat[[:blank:]]*\|\|/d' \
    "${XDIR}/${target}"
echo '--> Search for vestiges of array-flat-polyfill' 1>&2
if grep -ErinI 'defineProperty\(Array\.prototype,[[:blank:]]*.flat' \
    "${XDIR}/src/snakemake/assets"
then
  echo 'MANUAL AUDIT REQUIRED' 1>&2
  exit 1
fi
# Remove license file and the directory containing it
rm -rv "${XDIR}/src/snakemake/assets/data/array-flat-polyfill"
echo "--> Search for missed CC0-1.0 licenses" 1>&2
if grep -ErinI '\bCC0\b' "${XDIR}/src/snakemake/assets"
then
  echo 'MANUAL AUDIT REQUIRED' 1>&2
  exit 1
fi

echo "==== Archive assets ====" 1>&2
RESULT="${XDIR}-assets.tar.zst"
ls -ld "${XDIR}/src/snakemake/assets/"
# https://www.gnu.org/software/tar/manual/html_section/Reproducibility.html
TZ=UTC LC_ALL=C tar \
    --create \
    --sort=name \
    --format=posix \
    --numeric-owner --owner=0 --group=0 \
    --mode=go+u,go-w \
    --pax-option='delete=atime,delete=ctime' \
    --clamp-mtime --mtime="@${MTIME}" \
    --directory="${XDIR}" \
    src/snakemake/assets/data |
  zstdmt --ultra -22 > "${RESULT}"

mv -v "${RESULT}" "${DIST_GIT}"
