#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
fixture=$(mktemp -d)
trap 'rm -rf "$fixture"' EXIT

old="$fixture/old"
new="$fixture/new"
mkdir -p "$old/assets" "$old/.compatibility-manifests" "$new/assets"
printf 'old-current.js\nshared.js\n' > "$old/.release-assets"
printf 'older-one.js\n' > "$old/.compatibility-manifests/1.assets"
printf 'too-old.js\n' > "$old/.compatibility-manifests/2.assets"
for asset in old-current.js shared.js older-one.js too-old.js orphan.js; do printf '%s\n' "$asset" > "$old/assets/$asset"; done
printf 'new-current.js\nshared.js\n' > "$new/.release-assets"
printf 'new-current.js\n' > "$new/assets/new-current.js"
cp "$old/assets/shared.js" "$new/assets/shared.js"

output=$("$SCRIPT_DIR/prepare-web-release-tree.sh" "$new" "$old" 2)
test "$output" = 'web_release_tree=ok current_assets=2 compatibility_assets=3 compatibility_generations=2 served_assets=4'
test -f "$new/assets/old-current.js"
test -f "$new/assets/older-one.js"
test ! -e "$new/assets/too-old.js"
test ! -e "$new/assets/orphan.js"
test "$(cat "$new/.compatibility-manifests/1.assets")" = "$(cat "$old/.release-assets")"
test "$(cat "$new/.compatibility-manifests/2.assets")" = "$(cat "$old/.compatibility-manifests/1.assets")"

unsafe="$fixture/unsafe"
cp -R "$new" "$unsafe"
printf '../secret.js\n' > "$old/.release-assets"
if "$SCRIPT_DIR/prepare-web-release-tree.sh" "$unsafe" "$old" 2 > "$fixture/unsafe.out" 2>&1; then
  printf 'expected an unsafe asset to fail\n' >&2
  exit 1
fi
grep -q 'unsafe release asset' "$fixture/unsafe.out"

printf 'prepare-web-release tests passed\n'
