#!/usr/bin/env bash
# Builds Nuhet's compiled assets (Laravel Mix) for one commit and packages them for
# production (#3598). The compiled bundles are git-ignored, so a git deploy never updates
# them; this tarball is how they reach the server. See docs/ops/asset-release.md.
#
# The build runs in a fresh `git archive` export of the commit, so local edits, a stale
# node_modules or old files in public/ cannot leak into the package.
#
# Usage:
#   tools/release/build-assets.sh --editor-from DIR [--rev REV] [--out DIR] [--keep-build]
#   tools/release/build-assets.sh --without-editor  [--rev REV] [--out DIR] [--keep-build]
#
#   --rev REV          commit to build (default HEAD). Use the commit that will be deployed.
#   --out DIR          where the tarball goes (default /tmp/nuhet-asset-releases).
#   --editor-from DIR  an already built public/newsletter-editor directory to ship with the
#                      build (the editor has its own build, see docs/ops/newsletter-editor-ui-3967.md).
#                      Its files are copied and their entries merged into mix-manifest.json.
#   --without-editor   ship no editor files. The new mix-manifest.json then has no
#                      /newsletter-editor entries, so /newsletter-editor stops loading until an
#                      editor build is installed. Only for servers where the editor is unused.
#   --keep-build       keep the temporary build directory for inspection.
#
# Output: <out>/nuhet-assets-<short>.tar.gz, .tar.gz.sha256 and .json (the file list).
set -euo pipefail
umask 022

die() { echo "build-assets: $*" >&2; exit 2; }

rev=HEAD
out=/tmp/nuhet-asset-releases
editor_from=
without_editor=0
keep_build=0
while [ $# -gt 0 ]; do
    case "$1" in
        --rev) rev=${2:?--rev needs a value}; shift 2 ;;
        --out) out=${2:?--out needs a value}; shift 2 ;;
        --editor-from) editor_from=${2:?--editor-from needs a directory}; shift 2 ;;
        --without-editor) without_editor=1; shift ;;
        --keep-build) keep_build=1; shift ;;
        -h|--help) sed -n '2,24p' "$0"; exit 0 ;;
        *) die "unknown argument: $1 (see --help)" ;;
    esac
done

if [ -n "$editor_from" ] && [ "$without_editor" = 1 ]; then die "use --editor-from or --without-editor, not both"; fi
if [ -z "$editor_from" ] && [ "$without_editor" = 0 ]; then
    die "say what to do with the newsletter editor: --editor-from DIR or --without-editor (see --help)"
fi
for tool in git node npm npx tar gzip sha256sum; do
    command -v "$tool" >/dev/null || die "$tool is not installed"
done

here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
repo=$(git -C "$here" rev-parse --show-toplevel)
commit=$(git -C "$repo" rev-parse --verify "${rev}^{commit}") || die "unknown commit: $rev"
short=${commit:0:8}
commit_time=$(git -C "$repo" show -s --format=%ct "$commit")
mkdir -p "$out"
out=$(cd "$out" && pwd)
[ -e "$out/nuhet-assets-$short.tar.gz" ] && die "$out/nuhet-assets-$short.tar.gz already exists; move it away first"

if [ -n "$editor_from" ]; then
    [ -d "$editor_from" ] || die "--editor-from $editor_from is not a directory"
    editor_from=$(cd "$editor_from" && pwd)
    for entry in workspace.js workspace.css starter-picker.js starter-picker.css controls.css; do
        [ -s "$editor_from/$entry" ] || die "--editor-from has no $entry; is it a built public/newsletter-editor directory?"
    done
    [ -z "$(find "$editor_from" -type l -print -quit)" ] || die "--editor-from contains symbolic links"
fi

build=$(mktemp -d "${TMPDIR:-/tmp}/nuhet-asset-build-XXXXXX")
cleanup() {
    if [ "$keep_build" = 1 ]; then echo "Build directory kept: $build"; else rm -rf "$build"; fi
}
trap cleanup EXIT
src="$build/src"
mkdir -p "$src"

echo "== Exporting $commit"
git -C "$repo" archive --format=tar "$commit" | tar -x -C "$src"
# Everything under public/ that git delivers, so the packager can tell built files apart.
(cd "$src" && find public -type f -print0 | sort -z | xargs -0 -r sha256sum) > "$build/public-before.sha256"

cd "$src"
echo "== npm ci (node $(node --version), npm $(npm --version))"
npm ci --no-audit --no-fund
echo "== mix --production"
npx --no-install mix --production

editor_mode=excluded
editor_source=
if [ -n "$editor_from" ]; then
    echo "== Adding the newsletter editor build from $editor_from"
    mkdir -p public/newsletter-editor
    cp -R "$editor_from/." public/newsletter-editor/
    node tools/newsletter-editor/manifest.mjs
    editor_mode=included
    editor_source="$editor_from ($(find "$editor_from" -type f | wc -l) files)"
fi

echo "== Verifying and packaging"
# The packager comes from this checkout, so an older commit (without it) can still be built.
node "$here/package-assets.mjs" \
    --src "$src" --before "$build/public-before.sha256" \
    --commit "$commit" --commit-time "$commit_time" --out "$out" \
    --editor "$editor_mode" --editor-source "$editor_source" --npm "$(npm --version)"

echo "== Checking the tarball"
check="$build/check"
mkdir -p "$check"
(cd "$out" && sha256sum -c --quiet "nuhet-assets-$short.tar.gz.sha256")
tar -xzf "$out/nuhet-assets-$short.tar.gz" -C "$check"
[ "$(ls -A "$check")" = "nuhet-assets-$short" ] || die "tarball has an unexpected top level"
(cd "$check/nuhet-assets-$short" && sha256sum -c --quiet SHA256SUMS)
extra=$(cd "$check/nuhet-assets-$short" && find . -type f ! -path './public/*' ! -name SHA256SUMS ! -name release-assets.json)
[ -z "$extra" ] || die "tarball has files outside public/: $extra"
listed=$(wc -l < "$check/nuhet-assets-$short/SHA256SUMS")
packed=$(cd "$check/nuhet-assets-$short" && find public -type f | wc -l)
[ "$listed" = "$packed" ] || die "SHA256SUMS lists $listed files but the tarball has $packed"

# Built files should be git-ignored, or they show up as untracked on the server and can block a
# later pull that starts tracking them.
git -C "$src" init -q
(cd "$check/nuhet-assets-$short" && find public -type f | sort) > "$build/packed.txt"
(cd "$src" && git check-ignore --no-index --stdin < "$build/packed.txt" || true) | sort > "$build/ignored.txt"
not_ignored=$(comm -23 "$build/packed.txt" "$build/ignored.txt")
if [ -n "$not_ignored" ]; then
    echo "WARNING: these built files are not in .gitignore:" >&2
    echo "$not_ignored" | sed 's/^/  /' >&2
fi

echo
echo "Built $packed files for $commit"
echo "  $out/nuhet-assets-$short.tar.gz"
echo "  sha256 $(cut -d' ' -f1 "$out/nuhet-assets-$short.tar.gz.sha256")"
echo "Install with tools/release/install-assets.sh (docs/ops/asset-release.md)."
