#!/bin/bash

set -eu

igconf isy image_idp_enable || exit 0

outdir=${IGconf_image_outputdir:-}
[[ -n "$outdir" && -f "$outdir/image.json" ]] || exit 0

echo "Creating IDP archive..."

# Take the payload list from image.json itself so the archive always holds
# exactly what the consumer resolves. A/B layouts legitimately reference one
# sparse image from several partitions (boot_a and boot_b both point at
# boot.vfat.sparse), hence the dedupe; sorted for a reproducible tar.
simages=$(python3 -c '
import json, sys

with open(sys.argv[1]) as f:
    desc = json.load(f)

pimages = desc.get("layout", {}).get("partitionimages", {})
names = {p["simage"] for p in pimages.values()
         if isinstance(p, dict) and p.get("simage")}
if not names:
    sys.exit("image.json declares no partition sparse images")
print("\n".join(sorted(names)))
' "$outdir/image.json")

idp_files=("image.json")
while IFS= read -r s; do
    [[ -n "$s" ]] || continue
    # A referenced payload that is absent yields an archive the provisioner
    # rejects as incomplete, so fail here rather than ship it.
    [[ -f "$outdir/${s}" ]] || \
       die "IDP archive incomplete: image.json references missing $s"
    idp_files+=("$s")
done <<< "$simages"


# Create the bundle, preserving sparseness, compressing if enabled
base="${IGconf_image_name:-image}.idp.tar"
case "$IGconf_deploy_compression" in
   zstd)
      archive_name="${base}.zst"
      tar -S -C "$outdir" -cf - "${idp_files[@]}" \
         | zstd -f -o "${1}/$archive_name"
      ;;
   *)
      archive_name="${base}"
      tar -S -C "$outdir" -cf "${1}/$archive_name" \
         "${idp_files[@]}"
      ;;
esac
echo "Done: ${1}/$archive_name"
