#!/usr/bin/env bash
set -euo pipefail

version="${1:-3.4.0+dfsg1}"
if [ "$#" -gt 1 ]; then
  echo "usage: $0 [VERSION]" >&2
  exit 2
fi
if [[ "${version}" != *+dfsg* ]]; then
  echo "DFSG source version must include +dfsg" >&2
  exit 2
fi
upstream_version="${version%%+dfsg*}"
package="fonts-nerd-symbols"
release="v${upstream_version}"
upstream_repo="https://github.com/ryanoasis/nerd-fonts.git"
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
workdir="$(mktemp -d)"
trap 'rm -rf "${workdir}"' EXIT

checkout="${workdir}/nerd-fonts"
source="${workdir}/${package}-${version}"
orig="${repo_root}/../${package}_${version}.orig.tar.xz"

mkdir -p "${source}/upstream-src"

git clone --depth 1 --branch "${release}" --filter=blob:none --sparse "${upstream_repo}" "${checkout}"
git -C "${checkout}" sparse-checkout set --no-cone \
  /font-patcher \
  /LICENSE \
  /license-audit.md \
  /10-nerd-font-symbols.conf \
  /bin/scripts/generate-original-source.py \
  /bin/scripts/lib \
  /src/glyphs \
  /src/svgs \
  /src/unpatched-fonts/NerdFontsSymbolsOnly

cp -a \
  "${checkout}/font-patcher" \
  "${checkout}/LICENSE" \
  "${checkout}/license-audit.md" \
  "${checkout}/10-nerd-font-symbols.conf" \
  "${checkout}/bin" \
  "${checkout}/src" \
  "${source}/upstream-src/"

rm -rf \
  "${source}/upstream-src/src/glyphs/font-awesome" \
  "${source}/upstream-src/src/glyphs/materialdesign" \
  "${source}/upstream-src/src/glyphs/weather-icons"
rm -f \
  "${source}/upstream-src/src/glyphs/font-awesome-extension.ttf" \
  "${source}/upstream-src/src/glyphs/font-logos.ttf" \
  "${source}/upstream-src/bin/scripts/lib/i_logos.sh"

# The orig tarball is upstream content only. Keep it reproducible across Debian revisions.
tar --sort=name --owner=0 --group=0 --numeric-owner --mtime="@0" \
  -C "${workdir}" -cJf "${orig}" "${package}-${version}"

echo "Prepared ${orig}"
echo "Import with: gbp import-orig --no-interactive --upstream-version ${version} --pristine-tar ${orig}"
